繁体   English   中英

Django中如何将一对多关系的多个值解析为HTML模板?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM