简体   繁体   中英

Best practice for joining MySQL tables in Django

I have two models like this in my Django project.

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()

Of course a product can have 2 or more pictures. How can I get a all products with all related every single image in my view and pass the result as a context to the template?

I searched and tried these: prefetch_related , select_related , raw sql query and couple of suggested ways, but cannot get the result.

You may use prefetch_related to optimise the query

Product.objects.filter(sub_category = sub_category_id).prefetch_related('productimage_set')

Then, in the template

{% for image in product.productimage_set %} 
display image here
{% endfor %}

You may alternately set a related_name in the foreign-key, like

product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_images")

and then in the view,

Product.objects.filter(sub_category = sub_category_id).prefetch_related('product_images')

end then in the template

{% for image in product.product_images %} 
    display image here
 {% endfor %}

Refer ForeignKey.related_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM