0

I have a list of all products which belong to different categories.

model.py

 class Product(models.Model):
        product_name = models.CharField(max_length=50,null=True, blank=True)
        details = models.CharField(max_length=100, null=True, blank=True)
        company_name = models.CharField(max_length=50,null=True, blank=True)
        category = models.ForeignKey(ProductClass,null=True, blank=True)

Category is a ForeignKey of ProductClass.

Now I want a list of all different categories. I do not want a list of repetitive categories. For that I tried obj = CustomerLeads.objects.all()

obj = Product.objects.all()


    c = []
        for i in obj:
            c.append(i.item_required)

        cat = set(c)
        return JsonResponse({'data':cat})

I am getting error set([<ProductClass: accessories>, <ProductClass: other>]) is not JSON serializable

How can I get a list of all different categories?

das-g
  • 9,718
  • 4
  • 38
  • 80
vikrant Verma
  • 478
  • 3
  • 8
  • 17

1 Answers1

0

distinct() eliminates the duplicate element of queryset .

values_list(*field, flat=True) are used to return the values as list.

 Product.objects.values_list('category__category_name', flat=True).distinct()

#output
[u'Lamps', u'Professional', u'LED', u'Automotive']

Reference

Community
  • 1
  • 1
Ibrahim Kasim
  • 1,414
  • 1
  • 10
  • 9