0

我知道这很愚蠢,但是...

我有两个模型类

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 __unicode__(self):
        return self.caption

我想要三种类型的查询

  1. 从该图库中使用一个“图像”获取所有“图库”
  2. 从单个图库中获取所有图像

第三个我可以处理从“图像”中获取特定图像

4

3 回答 3

2

对于#1:每张图片只有一个画廊。如果你有一个图像对象img,那么它的画廊是

gallery = img.gallery

对于#2:要获取画廊的所有图像:

imgs = gallery.image_set.all()
于 2011-08-04T20:38:20.567 回答
1

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 %}    
于 2011-08-04T20:58:54.707 回答
1

对于#2:

如果 g 是画廊,则使用:

g.image_set.all()
于 2011-08-04T20:32:51.967 回答