How can I have a query set in the DetailView?

Question:

Field 'id' expected a number but got <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x1024f3c70>.

This is the error message and

class ProductDetail(DetailView):
  model = Product

  def get_context_data(self, **kwargs):
    context = super(ProductDetail, self).get_context_data()
    context['related_products'] = Product.objects.filter(category=Product.category)
    context['categories'] = Category.objects.all()
    context['no_category_post_count'] = Product.objects.filter(category=None).count
    return context

this is my views.py. A page that shows a product and related items is what I want to present. My questions are 1. Am I not allowed to bring a query set in the DetailView? 2. Then should I use ListView to do so?

Asked By: notagenius

||

Answers:

You access the object with self.object, so:

class ProductDetail(DetailView):
    model = Product

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['related_products'] = Product.objects.filter(
            category_id=self.object.category_id
        )
        context['categories'] = Category.objects.all()
        context['no_category_post_count'] = Product.objects.filter(
            category=None
        ).count()
        return context

or perhaps shorter:

class ProductDetail(DetailView):
    model = Product

    def get_context_data(self, *args, **kwargs):
        return super().get_context_data(
            *args,
            **kwargs,
            related_products=Product.objects.filter(
                category_id=self.object.category_id
            ),
            categories=Category.objects.all(),
            no_category_post_count=Product.objects.filter(category=None).count()
        )
Answered By: Willem Van Onsem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.