Filter model without using distinct method

Question:

I have a model with a list of products. Each product has an ID, price, brand, etc. I want return all the objects of the model where brand name is distinct. I am currently using django’s built-in SQLite, so it does not support something like

products = Product.objects.all().distinct('brand')

Is there another way of returning all the objects where the brand name is distinct?

Asked By: rastawolf

||

Answers:

Try Product.objects.order_by('brand').distinct('brand')

When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order. Refer

Answered By: Hrishi

try this

products = set(Product.objects.values_list('brand'))
Answered By: Ajay K

Well you can do it with 2 different methods:

  1. def MethodName(self):

    query = """
         SELECT DISTINCT brand FROM Product;
         """
    self.execute(query)
    
    1. products = Product.objects.raw("""
      SELECT DISTINCT brand FROM Product;
      """)

Please reply to this message If you have any difficulties fetching.

Answered By: Naser Fazal khan

As SQLight doesn’t support .distinct('field') you need to do this directly in python. For example:

products = list({p.brand: p for p in Product.objects.all()}.values())
Answered By: Yevhen Kuzmovych

Ok, so try

distinctBrands = Product.objects.values('brand').annotate(count=Count('brand')).filter(count=1)

products = Products.objects.filter(
    brand__in=distinctBrands 
).all()
Answered By: White Wizard
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.