[英]How to parse the many values of one-to-many relationship into HTML template in Django?
我在 Django 中有一對多的關系:
class Listing(models.Model):
title = models.CharField(max_length=60)
class Images(models.Model):
listings = models.ForeignKey(Listing, on_delete=models.CASCADE)
image_urls = models.URLField(max_length = 200)
我定義了以下視圖:
from .models import Listing, Images
def index(request):
All_Listings = Listing.objects.filter(isActive=True)
return render(request, "index.html", {
"All_Listings": All_Listings,
"Images" : Images
})
現在對於每個列表,我想在我的 HTML 中顯示所有相關圖像。 我試圖做以下事情:
{% extends "layout.html" %}
{% block body %}
{% for listing in All_Listings %}
<h2>{{ list(Images.objects.filter(listings_id=2)) }}<h2>
{% endfor%}
{% endblock %}
(If this works, than later on I will replace 2 with listing.id)
這將返回以下錯誤:
Exception Type: TemplateSyntaxError
Exception Value: Could not parse the remainder: '(Images.objects.filter(listings_id=2))' from 'list(Images.objects.filter(listings_id=2))'
但是,當我從終端運行它時,它可以工作:
>>> list(Images.objects.filter(listings_id=2))
[<Images: https://www.kettererkunst.com/still/kunst/pic570/531/422000352-4.jpg>, <Images: https://www.kettererkunst.com/still/kunst/pic570/531/422000352-1.jpg>]
我應該如何處理這個?
您可以創建@property 圖像列表 class,並查詢其中的所有相關圖像。
class Listing(models.Model):
title = models.CharField(max_length=60)
@property
def images(self):
return Images.objects.filter(listings=self)
class Images(models.Model):
listings = models.ForeignKey(Listing, on_delete=models.CASCADE)
image_urls = models.URLField(max_length = 200)
然后在模板中調用listing.images
:
{% for listing in All_Listings %}
{%for image in listening.images%}
{{ image }}
{% endfor%}
{% endfor%}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.