Django filter the model on ManyToMany count?

后端 未结 4 573
慢半拍i
慢半拍i 2020-12-13 23:30

Suppose I have something like this in my models.py:

class Hipster(models.Model):
  name = CharField(max_length=50)

class Party(models.Model):
  organiser =          


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 23:59

    If this works this is how I would do it.

    Best way can mean a lot of things: best performance, most maintainable, etc. Therefore I will not say this is the best way, but I like to stick to the ORM features as much as possible since it seems more maintainable.

    from django.db.models import Count
    
    user = Hipster.objects.get(pk=1) 
    hip_parties = (Party.objects.annotate(num_participants=Count('participants'))
                                .filter(organiser=user, num_participants__gt=0))
    

提交回复
热议问题