python - How to get single related object after filter -
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 filter parents based on children fields:
parent.objects.filter(children__first=true)
this generates following sql:
select app_parent.* app_parent inner join app_child on app_parent.id = app_child.parent_id app_child.first = true
after got parent fields but want related child fields sql that:
select app_parent.*, app_child.* app_parent inner join app_child on app_parent.id = app_child.parent_id app_child.first = true
and via django orm. ideas?
update
i think have nice workaround
parents = parent.objects.filter(children__first=true).prefetch_related('children') \ .extra(select={'child_id': '"app_child"."id"'}) parent in parents: parent.child = [child 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')
child.objects.filter(first=true).select_related('parent')
Comments
Post a Comment