Django 根据 ManyToMany 计数过滤模型?

发布于 2024-12-11 20:39:45 字数 475 浏览 0 评论 0原文

假设我的 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")

现在在我的 views.py 中,我想做一个查询,为有超过 0 名参与者的用户获取聚会。

也许是这样的:

user = Hipster.get(pk=1) 
hip_parties = Party.objects.filter(organiser=user, len(participants) > 0)

最好的方法是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一萌ing 2024-12-18 20:39:45

如果这有效的话,我就会这样做。

最好的方法可以意味着很多东西:最好的性能,最可维护等。因此我不会说这是最好的方法,但我喜欢尽可能坚持 ORM 功能,因为它看起来更容易维护。

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))

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))
零度° 2024-12-18 20:39:45
Party.objects.filter(organizer=user, participants__isnull=False)
Party.objects.filter(organizer=user, participants=None)
Party.objects.filter(organizer=user, participants__isnull=False)
Party.objects.filter(organizer=user, participants=None)
棒棒糖 2024-12-18 20:39:45

使用 exclude 更容易:

# organized by user and has more than 0 participants
Party.objects.filter(organizer=user).exclude(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

爱已欠费 2024-12-18 20:39:45

源自 @Yuji-'Tomita'-Tomita 答案,我还添加了 .distinct('id') 以排除重复记录:

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

因此,每一方仅列出一次。

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.

ˉ厌 2024-12-18 20:39:45

当我尝试返回在多域字段中至少有一个对象的查询集时,我使用以下方法:
首先,返回所有可能的多对多对象:

profiles = Profile.objects.all()

接下来,通过仅返回包含至少一个配置文件的查询集来过滤模型:

hid_parties = Party.objects.filter(profiles__in=profiles)

要在一行中执行上述操作:

hid_parties = Party.objects.filter(profiles__in=Profile.objects.all())

您可以以常规方式进一步细化各个查询集,以进行更具体的过滤。
注意:这可能不是最有效的方法,但至少对我有用。

I use the following method when trying to return a queryset having at least one object in a manytomany field:
First, return all the possible manytomany objects:

profiles = Profile.objects.all()

Next, filter the model by returning only the queryset containing at least one of the profiles:

hid_parties = Party.objects.filter(profiles__in=profiles)

To do the above in a single line:

hid_parties = Party.objects.filter(profiles__in=Profile.objects.all())

You can further refine individual querysets the normal way for more specific filtering.
NOTE:This may not be the most effective way, but at least it works for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文