Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

django values_list() and image reverse foreign key

I have a problem with the images, they are not displayed in the template, can someone help me with some solution

class Product(models.Model): 
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    myshop = models.ForeignKey(MyShop, on_delete=models.CASCADE, related_name="shop_product")
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)

class ProductImage(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_image")
    image = models.ImageField(upload_to='products/images',
                          validators=[validate_image_file_extension, validate_file_size,
                                      FileExtensionValidator(['JPEG', 'JPG', 'PNG'])])

{% for product in products %}  
    {% for image in product.product_image.all %}
        {% if image.is_feature %}
            <img src="{{ image.image.url }}" alt="" width="80" height="80">
        {% endif %}
    {% endfor %}
{% endfor %}



products = Product.prod_obj.select_related(
        'myshop'
    ).filter(id__in=product_ids).values_list('myshop', 'title', 'description', 'product_image', named=True)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Don’t use .values_list() [Django-doc] or .values() [Django-doc]: it removes the model logic layer, and thus as a result, you can indeed no longer access .url.

Query with:

products = Product.prod_obj.select_related('myshop').prefetch_related(
    'product_image'
).filter(id__in=product_ids)

For more information, see this article on (over)use of .values() I wrote.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading