我有 5 个相关模型要显示在我的模板中。对于每一个Collection
我想显示所有Product
属于相应集合的(ProductCollection
)。我需要为每个产品提供的信息是:名称 ( ProductAlias
) 和默认图像 ( ProductImage
)。
原始查询应该是这样的:
SELECT c.name, pa.name, pi.image
FROM Collection c JOIN ProductCollection pc ON c.collection_id = pc.collection_id
JOIN Product p ON pc.product_id = p.product_id
JOIN ProductAlias pa on p.product_id = pa.product_id
JOIN ProductImage pi on p.product_id = pi.product_id
WHERE pi.default = 'True' and pa.market_id = 1
models.py
:
class Collection(models.Model):
name = models.CharField()
class Product(models.Model):
video = models.URLField()
class ProductCollection(models.Model):
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
class ProductAlias(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
market = models.ForeignKey(Market, on_delete=models.CASCADE)
name = models.CharField()
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
image = models.ImageField()
default = models.BooleanField()
我将产品的名称分成另一个型号,因为 1 种产品有很多名称,具体取决于它们的销售地区。一个产品也有很多图片。但我只需要全局名称 ( market_id = 1
) 和default = True
每个Product
.
我目前尝试views.py
使用基于函数的视图(还没有应用过滤器,因为我在模板渲染期间已经得到了 ValueError):
def collection_view(request):
# tried to chain the prefetch_related on multiple models but failed.
collections = Collection.objects.prefetch_related('productcollection__product__id', 'productalias_set', 'productimage_set').all()
context = { 'collection_list': collections }
return render(request, 'product_visualizers/collection.html', context)
我目前对模板的尝试collection.html
:
{% for collection in collection_list %}
<h3>{{ collection.name }}</h3>
{% for pair in collection.productcollection_set.all %} # what should I loop here to show the product name and product image?
<p>{{ pair.product.product_id }}</p> # tried to display the product_id but failed.
<p>{{ productalias_name }}</p> # product name.
<img src="{{ image.url }}"> # product image.
{% endfor %}
{% endfor %}
您的问题不是由使用预取/选择相关引起的。这些只是为了减少重复查询。你pair.product.product_id
应该是pair.product.id
根据您设置模型的方式,您有多个 ProductAliases 对应一个 Product,多个 ProductImages 对应一个 Product。您需要遍历他们的两个集合以获取图像和名称字段。
{% for alias in pair.product.productalias_set.all %}
{{ alias.name }}
{% endfor %}
{% for product_image in pair.product.productimage_set.all %}
{{ product_image.image }}
{% endfor %}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句