当前位置: 动力学知识库 > 问答 > 编程问答 >

Django filter the model on ManyToMany count?

问题描述:

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

class Hipster(models.Model):

name = CharField(max_length=50)

class Party(models.Model):

organiser = models.ForeignKey()

participants = models.ManyToManyField(Profile, related_name="participants")

Now in my views.py I would like to do a query which would fetch a party for the user where there are more than 0 participants.

Something like this maybe:

user = Hipster.get(pk=1)

hip_parties = Party.objects.filter(organiser=user, len(participants) > 0)

What's the best way of doing it?

网友答案:

If this works this is how I would do it. Best way can mean a lot of things best performance, most maintainable, etc. Therefor I will not say this is the best way. However 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.get(pk=1) 
hip_parties = Party.objects.annotate(num_participants=Count('participants')) \
    .filter(organiser=user, num_participants__gt=0)
网友答案:
Party.objects.filter(organizer=user, participants__isnull=False)
Party.objects.filter(organizer=user, participants=None)
网友答案:

Easier with exclude:

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

Also returns distinct results

分享给朋友:
您可能感兴趣的文章:
随机阅读: