Django 在多对多计数上过滤模型? [英] Django filter the model on ManyToMany count?

查看:31
本文介绍了Django 在多对多计数上过滤模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的models.py中有这样的东西:

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

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

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.

可能是这样的:

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

最好的方法是什么?

推荐答案

如果可行,我会这样做.

If this works this is how I would do it.

最好的方式意味着很多事情:最好的性能、最易维护等.因此我不会说这是最好的方式,但我喜欢尽可能地坚持 ORM 特性,因为它看起来更易于维护.

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

这篇关于Django 在多对多计数上过滤模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆