[Django]-How to check whether all the values of a database field are same using django queries

5👍

Can propose You count lines using filter

if Product.objects.all().count() == Product.objects.filter(price=price).count():
    pass

or use distinct

if Product.objects.all().products.distinct('price').count() == 1:
    pass

Note that this example works correctly on Portgres only.

Also You can Use annotate to calculate count I think

if Product.objects.all().values('price').annotate(Count('price')).count() == 1:
    pass
👤oleg

0👍

You can use distinct to find unique prices:

products = Product.objects.filter([some condition])
prices = products.values_list('price', flat=True).distinct()

Then check the length of prices.

👤iMom0

Leave a comment