How can filter parent based on children in django

蓝咒 提交于 2019-12-08 17:02:26

问题


I have this

from django.db import models

class Kid(models.Model):
    name = models.CharField(max_length=200)

class Toy(models.Model):
    name = models.CharField(max_length=200)
    owner = models.ForeignKey(Kid)

I have this queryset

kids = Kid.objects.all()

Now i want to filter kids whole toys has name star in it

and i am not able to decide which filter to apply

kids.filter(toys_set__icontains='star')


回答1:


Kid.objects.distinct().filter(toy__name__icontains='star')

Note the distinct() method. It is required because kid can have several "star" toys so without distinct() you will get duplicates in the queryset.

If you want to filter kids by number of found toys when use aggregation:

Kid.objects.distinct().filter(toy__name__icontains='star') \
                      .annotate(toys_num=Count('toy')).filter(toys_num__gt=4)


来源:https://stackoverflow.com/questions/28059987/how-can-filter-parent-based-on-children-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!