所以問題就出在這裏。想象兩種模式:攝影師和照片。嚴格的規則是,圖片只能有1位攝影師,所以在Photo中有攝影師的ForeignKey鏈接。現在ForeignKey和Django Template
class Photographer(models.Model):
name = models.CharField(max_length = 40)
class Photo(models.Model):
name = models.CharField(max_length = 40)
photographer = models.ForeignKey(Photographer)
我想顯示在主頁上最有名的攝影師用3張最流行的他的照片。所以它應該是這樣的:
# views.py
def main(request):
photographers = ...
return render_to_response("main_page.html", {
"photographers": photographers
})
#main_page.html
{% for photo in photographers.photo_set.all()[:3] %}
{{ photo.name }}
{% endfor %}
但Django模板系統不允許all()和[:3]。那麼最好的辦法是什麼?最明顯的解決方案是動態創建對象(從攝影師和照片創建數組並將其傳遞給模板),但我不認爲這是一個好方法。
請不要只是參考我Django的手冊,我仔細閱讀,但無法找到答案...
我剛剛添加了一個答案,其實或多或少是你在評論中所說的:-) – 2009-08-15 18:08:02