tags:

views:

167

answers:

1

I'm looking to narrow a query set for a form field that has a foreignkey to the User's table down to the group that a user belongs to.

The groups have been previously associated by me. The model might have something like the following:

    myuser = models.ForeignKey(User)

And my ModelForm is very bare bones:

class MyForm(ModelForm):
    class Meta:
     model = MyModel

So when I instantiate the form I do something like this in my views.py:

    form = MyForm()

Now my question is, how can I take the myuser field, and filter it so only users of group 'foo' show up.. something like:

form.fields["myuser"].queryset = ???

The query in SQL looks like this:

mysql> SELECT * from auth_user INNER JOIN auth_user_groups ON auth_user.id = auth_user_groups.user_id INNER JOIN auth_group ON auth_group.id = auth_user_groups.group_id WHERE auth_group.name = 'client';

I'd like to avoid using raw SQL though. Is it possible to do so?

+5  A: 

You'll want to use Django's convention for joining across relationships to join to the group table in your query set:

form.fields['myuser'].queryset = User.objects.filter(groups__name='foo')

If you want to see the generated query, you can do this:

qs = User.objects.filter(groups__name='foo')
print qs.query
Joe Holloway
Brilliant, thanks Joe. I posted the SQL for this above right as you posted the answer. Appreciate the feedback, works excellent.
randombits
No prob, I went back and edited it to show you how to print out the SQL for a query set so you can compare it to what you're expecting.
Joe Holloway