Django: How to filter Users that belong to a specific group

后端 未结 2 829
感动是毒
感动是毒 2020-12-09 08:10

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 previou

相关标签:
2条回答
  • 2020-12-09 08:29

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

    Firstly, I recommend giving your relationship a related_name. This makes the code more readable than what Django generates by default.

    class Group(models.Model):
        myuser = models.ForeignKey(User, related_name='groups')
    

    If you want only a single group, you can join across that relationship and compare the name field using either of these methods:

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

    If you want to qualify multiple groups, use the in clause:

    form.fields['myuser'].queryset = User.objects.filter(
        groups__name__in=['foo', 'bar'])
    

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

    qs = User.objects.filter(groups__name='foo')
    print qs.query 
    
    0 讨论(0)
  • 2020-12-09 08:35

    This is a really old question, but for those googling the answer to this (like I did), please know that the accepted answer is no longer 100% correct. A user can belong to multiple groups, so to correctly check if a user is in some group, you should do:

    qs = User.objects.filter(groups__name__in=['foo'])
    

    Of course, if you want to check for multiple groups, you can add those to the list:

    qs = User.objects.filter(groups__name__in=['foo', 'bar'])
    
    0 讨论(0)
提交回复
热议问题