我的 Django 项目中有两个这样的模型。
class Product(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE)
sub_category = models.ForeignKey(ProductSubCategory, on_delete=models.CASCADE)
comment = models.TextField()
size = models.CharField(max_length=60)
price = models.FloatField(default=0)
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
alt = models.CharField(max_length=200)
picture = models.FileField()
当然,一个产品可以有 2 张或更多图片。 如何获取 View 中所有相关的每个图像的所有产品,并将结果作为上下文传递给模板?
我搜索并尝试了这些:
预取相关
,
选择相关
,
原始sql查询
和一些建议的方法,但无法得到结果。
最佳答案
您可以使用prefetch_lated
来优化查询
Product.objects.filter(sub_category = sub_category_id).prefetch_related('productimage_set')
然后,在模板中
{% for image in product.productimage_set %}
display image here
{% endfor %}
您也可以在外键中设置lated_name
,例如
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_images")
然后在 View 中,
Product.objects.filter(sub_category = sub_category_id).prefetch_related('product_images')
然后在模板中结束
{% for image in product.product_images %}
display image here
{% endfor %}
关于python - 在 Django 中连接 MySQL 表的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50070507/