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?
CodePudding user response:
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())
CodePudding user response:
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
CodePudding user response:
Well you can do it with 2 different methods:
def MethodName(self):
query = """ SELECT DISTINCT brand FROM Product; """ self.execute(query)
- products = Product.objects.raw(""" SELECT DISTINCT brand FROM Product; """)
Please reply to this message If you have any difficulties fetching.
CodePudding user response:
Ok, so try
distinctBrands = Product.objects.values('brand').annotate(count=Count('brand')).filter(count=1)
products = Products.objects.filter(
brand__in=distinctBrands
).all()
CodePudding user response:
try this
products = set(Product.objects.values_list('brand'))