C
C
cachealot2011-01-24 13:41:25
Django
cachealot, 2011-01-24 13:41:25

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


What comes to mind:

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


and run through the photos array, but how to do
for category in photos
for x,y in photos[category] in the template
?

do you really need to do
photos.append((gal.category, gal, p))

??

Answer the question

In order to leave comments, you need to log in

4 answer(s)
U
un1t, 2011-01-25
@cachealot

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

H
homm, 2011-01-24
@homm

Just select all the photos you want with select_related for galleries and categories, and in the template group them using the regroup tag .

U
un1t, 2011-01-24
@un1t

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/

S
savados, 2011-01-25
@savados

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 question

Ask a Question

731 491 924 answers to any question