开发者

django foreign key complex query

I know this is dumb but...

I have two model classes

class Gallery(models.Model):
    name = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published', auto_now_add=True)

    def __unicode__(self):
        return self.name


class Image(models.Model):
    gallery = models.ForeignKey(Gallery)
    image = models.ImageField(upload_to='gallery/%Y/%m/%d')
    caption = models.TextField(blank=True)
    up_date = models.DateTimeField(auto_now_add=True)

    def开发者_Python百科 __unicode__(self):
        return self.caption

I want three types of query

  1. Get all the "Gallery" with one "Image" from that gallery
  2. Get all the image from a single gallery

third one I can handle get a specific image from a "Image"


For #1: There's only one Gallery for each Image. If you have an image object img then the gallery for it is

gallery = img.gallery

For #2: To get all the images for a gallery:

imgs = gallery.image_set.all()


I think I understand what you're looking for.

Query #1

You want all galleries, along with a single image for each gallery. Since Django automatically allows you to access related objects you can accomplish this by simply retrieving all the galleries in your db.

select_related() automatically "follows" foreign-key relationships when it executes the query, which means later use of foreign-key relationships won't require database queries.

#selects all galleries ordered from newest to oldest
galleries = Gallery.objects.order_by('-pub_date').select_related() 

To get the first image from each gallery in your template, you would do this:

{% for gallery in galleries %}
    {{ gallery.name }}
    <img src="{{ gallery.image_set.all.0.image }}">
{% endfor %}

https://docs.djangoproject.com/en/dev/ref/models/querysets/

https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

Query #2

This actually works exactly the same as the previous query, but for only a single gallery.

gallery = Gallery.objects.get(id=gallery_id).select_related() 

In your template:

{% for image in gallery.image_set.all %}
    <img src="{{ image.image }}"><br>
    {{ image.caption }}
{% endfor %}    


For #2:

If g is a gallery, then use:

g.image_set.all()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜