rudiq
rudiq

Reputation: 15

How to get related objects

I have 2 models : -products -review

Every product has one or more reviews.

Question : How I can get this related object's in view and pass him into template.

def product_detail(request, id, slug):
    product = get_object_or_404(Product, id=id, slug=slug, available=True)
    cart_product_form = CartAddProductForm()
    reviews = Review.objects.filter()
    template = 'shop/product/detail.html'
    return render_to_response(template,
                              {'product': product,
                               'cart_product_form': cart_product_form,
                               'reviews': reviews})
class Review(models.Model):
    RATING_CHOICES = (
        (1, '1'),
        (2, '2'),
        (3, '3'),
        (4, '4'),
        (5, '5'),
    )
    product = models.ForeignKey(Product, on_delete=models.CASCADE, default=None)
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
    created = models.DateTimeField(auto_now_add=True, auto_now=False)
    text = models.TextField(max_length=500, blank=False)
    rating = models.IntegerField(choices=RATING_CHOICES, default=5)

    def __str__(self):
        return "%s" % self.user

Upvotes: 1

Views: 107

Answers (2)

Renan Caique
Renan Caique

Reputation: 23

You can filter, passing on the Review objects, the product you are trying to get:

  Review.objects.filter(product__id=productid)

This will retrieve all the reviews of that product, you can get this in some method of the view and pass to a template with a context

https://docs.djangoproject.com/en/2.2/ref/templates/api/#using-requestcontext https://docs.djangoproject.com/en/2.2/topics/class-based-views/generic-display/

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

How i can get this related object's in view and pass him into template.

You don't need to pass these in the template. In the template you can render these as:

{% for review in product.review_set.all %}
    {{ review.text }}
{% endfor %}

In case you want to render the related set of multiple items, it is better to use a .prefetch_related(..) [Django-doc] call to prefetch all the related objects in a single query.

Upvotes: 1

Related Questions