开发者

Django: query with ManyToManyField count?

In Django, how do I construct a COUNT query for a ManyToManyField?

My models are as follows, and I want to get all the people whose name starts with A and who are the lord or overlord of at least one Place, and order the results by name.

class Manor(models.Model):
    lord = models.ManyToManyField(Person, null=True, related_name="lord")
    overlord = models.ManyToManyField(Person, null=True, related_name="overlord")
class Person(models.Model):
    name = models.CharField(max_length=100)

So my query should look something like this... but how do I construct the third line?

people = Person.objects.filter(
       Q(name__istartswith='a'), 
       Q(lord.count > 0) | Q(overlord.coun开发者_JS百科t > 0) # pseudocode
).order_by('name'))


Actually it's not the count you're interested in here, but just whether or not there are any members in that relationship.

Q(lord__isnull=False) | Q(overlord__isnull=False) 


In this case, better resort to raw SQL.

for p in Person.objects.raw('SELECT * FROM myapp_person WHERE...'):
    print p
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜