如何使用 django 查询检查数据库字段的所有值是否相同

Shi*_*dla 3 python django orm django-queryset

我有一个如下所示的模型

Class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.IntegerField()
Run Code Online (Sandbox Code Playgroud)

那么假设我们4 product在数据库中有记录,是否有办法检查是否所有 4 个产品记录都有same price

我不想循环遍历所有产品,因为thousands数据库中可能有产品记录,这样做会成为性能问题。

所以我正在寻找类似使用内置 django 数据库 ORM 来执行此操作

check_whether_all_the_product_records_has_same_price_value = some django ORM operation......

if check_whether_all_the_product_records_has_same_price_value:
    # If all the Product table records(four) has the same price value 
    # return the starting record
   return check_whether_product_has_same_price_value(0)
Run Code Online (Sandbox Code Playgroud)

那么有人可以告诉我我们该怎么做吗?

ole*_*leg 5

可以建议您使用以下方式计算行数filter

if Product.objects.all().count() == Product.objects.filter(price=price).count():
    pass
Run Code Online (Sandbox Code Playgroud)

或使用distinct

if Product.objects.all().products.distinct('price').count() == 1:
    pass
Run Code Online (Sandbox Code Playgroud)

请注意,此示例仅在 Portgres 上正确运行。

我认为你也可以用来annotate计算计数

if Product.objects.all().values('price').annotate(Count('price')).count() == 1:
    pass
Run Code Online (Sandbox Code Playgroud)