简体   繁体   中英

Django Queryset: Check if parent model has a child/referring model

Models:

class Parent(models.Model)
  name = models.CharField(max_length=20L)

class Child(models.Model)
  parent_id = models.ForeignKey('Parent')
  name = models.CharField(max_length=20L)

How to get the list of parents that have a child?

My current solution now is by iterating the Parent-queryset then check if it has a child. Is there any clean solution about this query?

Thanks guys!

parentList = Child.objects.filter(parent_id__isnull=False).values_list('parent_id', flat=True)

parentList = list(set(parentList))

applied set to get Parent only once

This worked for me.

parents_id_that_have_childs = Child.objects.filter(parent_id__isnull=False).values_list('parent_id', flat=True)

parents = Parent.objects.filter(id__in=list(set(parents_id_that_have_childs)))

Let me explain:

in parents_id_that_have_childs you will have a list of unique ids of parents that, obviously, have child objs.

then in you just filter the Parents that have these ids.

parents = Parent.objects.filter(id__in=list(set(parents_id_that_have_childs)))

You really should have a look to django-mptt.

But regarding your question:

parents_with_child = Parent.objects.exclude(child_set=None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM