1

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
1
  • Why do you need to do it in the view, particularly? Either way, it would be product.review_set.all(), although in the template you don't need the parentheses. Commented Sep 12, 2019 at 18:44

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.