Вопрос

I got parent-children (1-n) model relation:

class Parent(models.Model):
    some_fields = models.IntegerField()

class Child(models.Model):
    parent = models.ForeignKey(Parent, relatend_name='children')
    first = models.BooleanField()
    second = models.BooleanField()

Now I filter parents based on children fields:

Parent.objects.filter(children__first=True)

This generates the following SQL:

SELECT app_parent.*
FROM app_parent
INNER JOIN app_child ON app_parent.id = app_child.parent_id 
WHERE app_child.first = TRUE

after that i got all Parent fields BUT I want the related Child fields too to get SQL like that:

SELECT app_parent.*, app_child.*
FROM app_parent
INNER JOIN app_child ON app_parent.id = app_child.parent_id 
WHERE app_child.first = TRUE

and get it via Django ORM. Any ideas?

UPDATE

I think I have nice workaround

parents = Parent.objects.filter(children__first=True).prefetch_related('children') \
.extra(select={'child_id': '"app_child"."id"'})
for parent in parents:
    parent.child = [child for child in parent.children.all() if child == parent.child_id][0]
Это было полезно?

Решение

You can use prefetch_related

Parent.objects.filter(children__first=True).prefetch_related('children')

Or select_related

Child.objects.filter(first=True).select_related('parent')

Другие советы

You have to use the fetch_related method for that and do the lookup the other way around unfortunately.

In this case it should be something like this:

first_children = Child.objects.filter(first=True).select_related('parent')
parents = [c.parent for c in first_children]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top