Django query with related models shows only fields of one model
I have three related models and want to make a query to get a combination of fields from all three models.
invoice_select = Ordered_item.objects.filter(oi_order = o_id).select_related()
generates the SQL-statement which I can check with the debug_toolbar. The SQL statement contains all fields of the related models.
Sending the result of the query to a html-file with
return render_to_response('invoice_select.html', {'invoice_select':invoice_select}
provides only the the expression which was defined for the Ordered_item model with:
def __unicode__(self):
return u'%s -- %s 开发者_开发知识库-- %s' % (self.oi_order, self.oi_pos, self.oi_item)
So the result of the query looks like:
{'invoice_select': [<Ordered_item: 1109231733 -- 01 -- BP-0516-aa>]}
which are exactly the fields defined in the def unicode(self):
What can I do to add more fields to the result of the query? Why do the fields in the SQL not show up in the result of the query ?
Any help will be highly appreciated.
You're just looking at the string representation of the object, which obviously uses the __unicode__
method. The fields are there, of course, if you access the objects directly.
The __unicode__ method is automagically being called when you refer to the object as a string. You could simply put the fields you care about in the __unicode__ method (assuming a Manufacturer model):
def __unicode__(self):
return u'%s -- %s -- %s -- %s -- %s' % (self.oi_order, self.oi_pos, self.oi_item,
self.manufacturer.name, self.manufacturer.favorite_stuffed_animal)
If you don't want to put that in the __unicode__ method, which does get used for other things, you can easily put it in some separate method and directly call that one rather than implicitly calling the __unicode__ one.
Also further note that if manufacturer might be null you need to handle that, perhaps with a try-catch block.
Here's what a separate method might look like:
def get_str(self):
return u'%s %s' % (self.oi_order, self.manufacturer.name)
And then if you have an oi instantiated:
str = oi.get_str()
精彩评论