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

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

问题描述

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

  class Hipster(models.Model):
name = CharField(max_length = 50)

class Party(models.Model):
organizer = models.ForeignKey()
Particip = models.ManyToManyField(Profile,related_name = 参与者)

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



这样做可能:

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

最好的做法是什么?

解决方案

如果这样工作,这是怎么做到的。最好的方法可以意味着很多事情最好的表现,最可维护的等等。所以我不会说这是最好的方法。但是,我喜欢尽可能多地遵守ORM功能,因为它似乎更易于维护。

 从django.db.models导入计数
user = Hipster.get(pk = 1)
hip_parties = Party.objects.annotate(num_participants = Count('participant'))\
.filter(organizer = user,num_participants__gt = 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?

解决方案

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)

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

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