Answer the question
In order to leave comments, you need to log in
Django, relationships, 3 tables relationship, newbie question
Good
afternoon, I smoothly switch from php to django.
After several consultations with psychologists, there were questions on the merits:
I want to realize my photo gallery with, well, you understand what we
have
Category
Gallery
Photos
I want to draw a conclusion like:
name of category photo gallery A photo A photo name of category photo gallery A photo A photo name of category photo gallery A photo A photo
def index(request): gallery = Gallery.objects.all().order_by('created') photos = {} for gal in gallery: p = port.photos.all() if(len(p)): photos[gal.category] = [] photos[gal.category].append((gal, p))
Answer the question
In order to leave comments, you need to log in
in the template it should look something like this
{% for gallery in galleries %}
gallery.photo_set.all
{% endfor %}
haven't tried it, but it seems to work
Just select all the photos you want with select_related for galleries and categories, and in the template group them using the regroup tag .
Try this
in view
galleries = Gallery.objects.all().order_by('created')
in the template:
for gallery in galleries:
gallery.photo_set().all().order_by('created') docs
with examples here: docs .djangoproject.com/en/1.2/topics/db/queries/
Your question has been answered, a couple more things for the future:
1. Use related_name. Then instead of gallery.photo_set.all you can write gallery.photos.all (or whatever name you like).
2. Specify sorting in Meta.
3. Here you can not write a view at all, but use direct_to_template.
4. If you need to make the same type of selections (such as the last 10 records sorted by date), then it is better to take these actions into a separate manager and call it. Encapsulation and all that. :-)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question