On May 5, 6:27 pm, Derek <gamesb...@gmail.com> wrote:
> I  have set of models, with relationships D -> C -> B -> A, where the
> "->" indicates a "many to one" relationship.
>
> I have been able to create a filtered queryset on child model D, based
> on a value in a parent model A, using the following syntax:
>
> my_query = D.objects.filter(C__B__A__name__icontains = "foo")
>
> where model A has a field called "name".
>
> I need to be able to display the value of the "name" field from A,
> along with the field attribute data from D in a template.
>
> I have therefore added the following to the end of my_query:
>
> .select_related('C__B__A__name')
>
> Assuming the template is called with the context containing:
>
> 'results': my_query
>
> then I can use {{ results.name }}, for example, to retrieve the value
> of the "name" field from model D.
>
> However I am unable to figure out the correct syntax for retrieving
> the value of the "name" field from related model A.
>
> I have tried  {{ results.C.B.A.name }} with no effect?
>
> What is the correct way to do this?
>
> Thanks
> Derek

Firstly, your select_related syntax is wrong. You don't need it to
access related objects, but it does help cut down on db queries.
However, it doesn't go down to field level, so you just want
'C__B__A'.

Secondly, your 'results' object is a queryset, so you *can't* do
'results.name' as you claim. A queryset is a collection of items, not
a single one, so 'results' as a whole doesn't have either 'name' or
'C' attributes. However, once you iterate through the queryset, each
individual item inside it does have both 'name' and 'C' attributes. So
this will work:

{% for result in results %}
    {{ result.name }} : {{ result.C.B.A.name }}
{% endfor %}

An easy way of exploring all this is via the shell - you could have
seen the result of your query there, and accessed the individual
objects and their attributes.
--
DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to