Django filter the model on ManyToMany count?

后端 未结 4 565
慢半拍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))
    
    0 讨论(0)
  • 2020-12-14 00:04

    Derived from @Yuji-'Tomita'-Tomita answer, I've also added .distinct('id') to exclude the duplitate records:

    Party.objects.filter(organizer=user, participants__isnull=False).distinct('id')
    

    Therefore, each party is listed only once.

    0 讨论(0)
  • 2020-12-14 00:07

    Easier with exclude:

    # organized by user and has more than 0 participants
    Party.objects.filter(organizer=user).exclude(participants=None)
    

    Also returns distinct results

    0 讨论(0)
  • 2020-12-14 00:15
    Party.objects.filter(organizer=user, participants__isnull=False)
    Party.objects.filter(organizer=user, participants=None)
    
    0 讨论(0)
提交回复
热议问题