ListView 中的 Django object_list 有两个模型

标签 django

我有两个模型,并且需要访问两个模型的属性。

模型.py

class Product(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product_title = models.CharField(max_length=255, default='product_title')    
    product_description = models.CharField(max_length=255, default='product_description')    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_active = models.BooleanField(default=True)
    product_view = models.IntegerField(default=0) 

    def __str__(self):
        return self.product_title

    def get_absolute_url(self):
        return reverse('product_change', kwargs={'pk': self.pk})

class ProductImages(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image_type = models.CharField(max_length=33,default='image_type')    
    image_file = models.ImageField(
        upload_to='images/',
        null=True,
        blank=True,
        default='magickhat-profile.jpg'
    )

ProductImages 是存储多个图像的模型。

View .py

class ProductListView(ListView):
    model = Product
    template_name = 'product_list.html'

产品列表.html

    ...
    {% for product in object_list %}
    <div class="product">
        {% include 'label_perfil.html' %}
        {% include 'data_product.html' %}
    </div>
    {% endfor %}
    ...

data_product.html

{% block data-product %}
<img src="{{ product.image_file }}"/>
{% endblock %}

Product 模型中的所有属性均可用,但如何访问 product.image_file 数据?返回空...

Django 3.2

最佳答案

每个产品可以有多个 ProductImage,因此您无需访问产品中的单个 image_file 属性,而是循环遍历该产品的所有 ProductImage 并从那里访问图像

data_product.html

{% block data-product %}
    {% for image in product.productimages_set.all %}
        <img src="{{ image.image_file.url }}"/>
    {% endfor %}
{% endblock %}

关于ListView 中的 Django object_list 有两个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70442828/

相关文章:

python - Daphne 服务器无法连接 HTTPS 上的 websockets

django - 南错误,但没有使用它。 "no South database module ' south.db.mysql'"

python - 你好 Django 重命名了我的应用程序的模型

python - 在 Django Rest Framework 中访问 View 集中的请求对象和序列化程序?

python - Django 条件唯一在一起

python - Amazon API 签名请求无法正常工作

django - 更改 pydev 中的端口

python - 删除 Django,因为我现在使用 VirtualEnv

python - 如何修复 Django-allauth settings.py contrib 语法错误?

python - 在 django admin 中创建对象时如何自动插入当前用户?