从模板调用方法

时间:2014-02-27 18:36:35

标签: python django python-2.7 django-models django-templates

我似乎在从django模板调用方法时遇到问题。鉴于模型:

class Gallery(models.Model):
    class Meta:
        verbose_name_plural = "Galerie"

    def photo_count(self):
        return self.photo_set.count()

    def random_image(self):
        return self.photo_set.get(id=random.randint(1,self.photo_count()))

    title = models.CharField(max_length=50)
    imgur_id = models.CharField(max_length=15)
    date_created = models.DateTimeField('Data utworzenia', auto_now=True)
    is_active = models.BooleanField()

    def __unicode__(self):
        return self.title

其中Gallery是外来关键照片 views.py:

def index(request):
    galleries = Gallery.objects.get(is_active=True)
    if galleries.count() is 0:
        messages.warning(request, "Niestety, żadna galeria nie jest aktywna, zaglądnij niebawem!")
        return redirect(reverse(home))
    elif galleries.count() is 1:
        return render(request, 'gallery/home.html', {'gallery': galleries})
    else:
         return render(request, 'gallery/index.html', {'galleries': galleries})

我想在模板中执行此操作:

{% for gallery in galleries %}
         {{ gallery.random_image }} <br />
{% endfor %}

我得到的结果是:

[ Photo object ]
[]
[]
[]

但是当我打电话时

{% for gallery in galleries %}
    {{ gallery.photo_count }} <br />
{% endfor %}

结果是正确的。

为什么这不起作用?

2 个答案:

答案 0 :(得分:0)

将@property添加到您的功能中。

@property
def photo_count(self):
    return self.photo_set.count()

答案 1 :(得分:0)

在我看来,你很复杂。

class Gallery(models.Model):
    class Meta:
        verbose_name_plural = "Galerie"

    def random_image(self):
        return self.photo_set.order_by('?')[0] if self.photo_set.count() else None

    title = models.CharField(max_length=50)
    imgur_id = models.CharField(max_length=15)
    date_created = models.DateTimeField('Data utworzenia', auto_now=True)
    is_active = models.BooleanField()

    def __unicode__(self):
        return self.title

并在模板中

{% for gallery in galleries %}
    {% if gallery.random_image %}
        {{ gallery.random_image }} <br />
    {% else %}
        No images found.
    {% endif %}
{% endfor %}

详细了解order_by here

请注意,?可能会略显沉重。如果是这样,请获取与此图库对象关联的photo_set的ID列表,并从此列表中获取随机ID,而不是 random.randint(1,self.photo_count())