Django 根据 ManyToMany 计数过滤模型?
假设我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果这有效的话,我就会这样做。
最好的方法可以意味着很多东西:最好的性能,最可维护等。因此我不会说这是最好的方法,但我喜欢尽可能坚持 ORM 功能,因为它看起来更容易维护。
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.
使用
exclude
更容易:还返回不同的结果
Easier with
exclude
:Also returns distinct results
源自 @Yuji-'Tomita'-Tomita 答案,我还添加了 .distinct('id') 以排除重复记录:
因此,每一方仅列出一次。
Derived from @Yuji-'Tomita'-Tomita answer, I've also added .distinct('id') to exclude the duplitate records:
Therefore, each party is listed only once.
当我尝试返回在多域字段中至少有一个对象的查询集时,我使用以下方法:
首先,返回所有可能的多对多对象:
接下来,通过仅返回包含至少一个配置文件的查询集来过滤模型:
要在一行中执行上述操作:
您可以以常规方式进一步细化各个查询集,以进行更具体的过滤。
注意:这可能不是最有效的方法,但至少对我有用。
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:
Next, filter the model by returning only the queryset containing at least one of the profiles:
To do the above in a single line:
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.