django:在这种情况下如何使用过滤器选项?

时间:2017-11-26 21:35:53

标签: python django templates filter

我有一个问题 这是我的代码
view.py

class testView(ListView):
    model = Photo
    template_name = 'photo/photo_detail.html'
    context_object_name = 'main_list'

    def get_context_data(self, **kwargs):
        context = super(testView, self).get_context_data(**kwargs)
        context['extra_value'] = Album.objects.filter(Album__name=Photo.album.name)
        return context

和model.py

class Album(models.Model):
    name = models.CharField(max_length=50)
    description = models.CharField('One Line Description', max_length=100, blank= True)
    owner = models.ForeignKey(User, null=True)
    Category = models.ForeignKey(Categories, null=True)
    price = models.CharField(max_length=20, null=True)
    productInfo = models.CharField(max_length=50, null=True)

    objects = models.Manager()
    second_manager = SecondAlbumManager()

    class Meta:
        ordering = ['name']
        verbose_name = 'Album'
        verbose_name_plural = 'Albums'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('photo:album_detail', args=(self.id,))

@python_2_unicode_compatible
class Photo(models.Model):
        album = models.ForeignKey(Album)
        title = models.CharField(max_length=50)
        image = ThumbnailImageField(upload_to='photo/%Y/%m')
        description = models.TextField('Photo Description', blank=True)
        upload_date = models.DateTimeField('Upload Date', auto_now_add=True)
        owner = models.ForeignKey(User, null=True)

    class Meta:
        ordering = ['title']
        verbose_name = 'Photo'
        verbose_name_plural = 'Photos'

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('photo:test', args=(self.id,))

Photo对象有ForeignKey(Album)所以,我想在模板中使用Filtered Album对象(photo_detail.html)

但是,我想比较一个Photo对象的Album外来值和Album__name并将其输出到模板,但我不知道如何更改Photo.album.name部分。请告诉我。

1 个答案:

答案 0 :(得分:0)

在模板中,您可以简单地使用属性album,例如:

{% for photo in  object_list %}
    {{ photo.album.name }} created by {{ photo.album.user.username }}
{% endfor %}

阅读docs

中的详细信息