【问题标题】:how to check whether all the values of a database field are same using django queries如何使用 django 查询检查数据库字段的所有值是否相同
【发布时间】:2013-11-09 20:06:49
【问题描述】:

我有一个像下面这样的模型

Class Product(models.Model):
    name = models.CharField(max_length=255)
    price = models.IntegerField()

假设我们在数据库中有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)

那么谁能告诉我我们该怎么做?

【问题讨论】:

  • 你到底为什么要这样做?它会像疯了一样减慢您的网站速度。
  • ohhhh,实际上有一些功能需要检查上述场景并根据上述场景退回产品,是的,我当然提到它会导致性能问题,所以在这里发布以获得优化如果可能的话解决方案?

标签: python django orm django-queryset


【解决方案1】:

您可以使用 distinct 来查找唯一价格:

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

然后检查价格的长度。

【讨论】:

    【解决方案2】:

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

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

    或使用distinct

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

    请注意,此示例仅适用于 Portgres。

    您也可以使用annotate 来计算我认为的计数

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

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 2012-05-20
      • 2021-03-20
      • 2020-12-07
      • 2017-03-01
      • 1970-01-01
      相关资源
      最近更新 更多