Django [SOLVED]: Access via ForeignKey to the image field of parrent model in QuerrySet [Django]

Django [SOLVED]: Access via ForeignKey to the image field of parrent model in QuerrySet [Django]

Home Forums Frameworks Django Tutorials Django [SOLVED]: Access via ForeignKey to the image field of parrent model in QuerrySet [Django]

Tagged: ,

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #246530

    Cloudy Point
    Keymaster

    QuestionQuestion

    I have this simplified model.py:

    class Product(models.Model):
        name = models.CharField()
        description = models.CharField()
    
    class ProductImage(models.Model):
        product = models.ForeignKey(Product,)
        photo = models.ImageField(upload_to="product_images/")
        is_main = models.BooleanField(default=False)
    

    An Product can have many ProductImage, but only ProductImage which has field is_main=True shall be rendered in a template together with all field of Product.

    The following data set from the views.py:

    products = Product.objects.all()
    

    So now I would want to do something like this in the template:

    {% for product in products %}
    <img class="card-img-top" src="{{ product.productimage_set.filter(is_main=True).photo }}" alt="Card image cap">
    <div class="card-body">
        <h4 class="card-title">{{ product.name }}</h4>
        <p class="card-text">{{ product.description }}</p>
        <a href="#" class="btn btn-primary">Go somewhere</a>
    </div>
    

    But obviously that’s not possible. Not from the template directly, at least.

    What is the proper way to get all the fields of Product and its image with attribute is_main=True inside the template?

    #246531

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    Easiest would be to keep the logic in the model and add a method or property

    class Product(models.Model):
        # ...
        def main_image(self):
            return self.productimage_set.get(is_main=True)
            # or more robust:
            # return self.productimage_set.filter(is_main=True).first()
    

    that you can access in the template:

     ... src="{{ product.main_image.photo.url }}  # don't forget the 'url'
    

    Source: https://stackoverflow.com/questions/47969153/access-via-foreignkey-to-the-image-field-of-parrent-model-in-querryset-django
    Author: schwobaseggl
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.