Monday, January 30, 2012

Re: Print list with select related with reverse foreign key

On Jan 29, 6:23 pm, Gabriel Carneiro Novaes <semprobl...@gmail.com>
wrote:
> I have two modelshttp://paste.ideaslabs.com/show/BN0e2z4NSa
>
> I want to print a list of ads (title,slug, and thumb_photo)
>
> How can I make this list, since the key is reverse?
>
> Something like this SQL:http://paste.ideaslabs.com/show/Iw8ii2noz

The problem is that by the model definitions you can have multiple
thumb-photos per ad. So, you can't use select related, as it can only
traverse relations that return one related item per row.

Now, there are some options:
- If you in fact want just one photo per add, then you should change
the foreign key to OneToOne key. After that select_related should
work.
- You can use a pre-release version of 1.4 and its
prefetch_related() feature which is meant exactly for this kind of
situation.
- You can do a manual prefetch. Basically you run two queries, then
do the join in Python code. I know there are snippets doing this, but
I can't find one currently. I hope some other reader of this list can
point out a snippet demonstrating this. This can be a little hard to
write if you haven't done this ever before.
- You can run one SQL query per list item, by using something like:
{% for adphoto in obj.adimage_set.all %}
{# display photo here #}
{% endfor %}
in your template.

- Anssi

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

No comments:

Post a Comment