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') 

or select_related

child.objects.filter(first=true).select_related('parent') 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -