来自ListView的Django object_list,包含两个模型



我有两个模型,需要从这两个模型访问属性。

型号.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'
)

CCD_ 1是用于存储多个图像的模型。

views.py

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

product_list.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

每个产品可能有多个ProductImages,因此您不会访问产品中的单个image_file属性,而是循环访问该产品的所有ProductImages并从那里访问

data_product.html

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

最新更新