Django ManyToMany filter()

后端 未结 3 1376
星月不相逢
星月不相逢 2020-11-27 13:00

I have a model:

class Zone(models.Model):
    name = models.CharField(max_length=128)
    users = models.ManyToManyField(User, related_name=\'zones\', null=T         


        
3条回答
  •  暖寄归人
    2020-11-27 13:21

    another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:

    UserZone = User.zones.through
    
    # for a single zone
    users_in_zone = User.objects.filter(
      id__in=UserZone.objects.filter(zone=zone1).values('user'))
    
    # for multiple zones
    users_in_zones = User.objects.filter(
      id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))
    

    it would be nice if it didn't need the .values('user') specified, but Django (version 3.0.7) seems to need it.

    the above code will end up generating SQL that looks something like:

    SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))
    

    which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned

提交回复
热议问题