tags:

views:

481

answers:

4

Hi all. This is probably a pretty n00b question, but i can't get it to work.

If i have following model:

from django.contrib.auth.models import User

class Entry(models.Model):
title = models.CharField()
users = models.ManyToManyField(User)

How would i get a list of all entry-titles of the currently logged in user? Something like:

list = Entry.objects.filter(users__????__contains = request.user)

?

Thanks in advance for helping me advance.

+2  A: 

Off the top of my head, I believe it might be along the lines of:

list = Entry.objects.filter(users__id__exact = request.user.pk)

or

list = Entry.objects.filter(users = request.user)

I believe either of those should work. For more info on many to many relationships check out the Django docs.

Alex Jillard
talk about missing the obvious, thanks for the insight
Jeroen Dierckx
A: 

You should be able to do this with:

Entry.objects.filter(users=request.user)

Django will sort out the correct join with the M2M table and add a WHERE clause limiting it to the current user.

Jarret Hardie
+1  A: 
Entry.objects.filter(users=request.user)

And there is an error in your code. CharField requires *max_length*.

del-boy
nice observation, i removed it to un-clutter the example without thinking about that
Jeroen Dierckx
+1  A: 

I find the following to be more elegant, but it's up to you.

request.user.entry_set.all()

EDIT: You shouldn't need to import the Entry model class every time you want to find entries associated with a user. Using user.entry_set avoids that hassle.

ozan