我有兩個模型,并且都需要訪問屬性。
模型.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 是一個模型來存盤多個影像。
視圖.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資料?那個回傳空...
姜戈 3.2
uj5u.com熱心網友回復:
每個產品可以有多個 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 %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389598.html
標籤:姜戈
