【问题标题】:Django Queryset get lowest/highest price! one to manyDjango Queryset 获得最低/最高价格!一对多
【发布时间】:2014-03-06 02:03:57
【问题描述】:

我有一些 Django 模型、一个 Product 类和一个 Price 类。一个产品可以有多个价格,但只有“最新”一个是当前价格!我有一个产品查询,我需要最低价格和最高价格,但只需要当前价格。如果一个产品有 2 个或更多价格,那只是我想要的最新价格!

class Product(models.Model):
    productname = models.CharField(max_length=1024)

class Price(models.Model):
    product = models.ForeignKey(Product)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    created = models.DateTimeField(auto_now_add=True)

查询集中的一个例子,我想要最低和最高,但只有当前价格。 “price__price__gt”也是如此。这也应该只是我希望它使用的当前价格。

Product.objects.filter(price__price__gt=1000).order_by("price")

【问题讨论】:

    标签: django django-models django-queryset


    【解决方案1】:

    这是您以最低价格获得产品的一种方式。

    在产品模型上创建一个“current_price”属性,

    class Product(models.Model):
        productname = models.CharField(max_length=1024)
    
        @property
        def current_price(self):
            """Returns last price if any prices exist, else None
            """
            if self.price.all():
                return self.price.order_by('-created')[0].price
    

    要使 current_price 属性正常工作,您需要在 Price 模型产品 fk 字段中添加“价格”相关名称,

    class Price(models.Model):
        product = models.ForeignKey(
            Product, related_name='price')
        price = models.DecimalField(max_digits=10, decimal_places=2)
        created = models.DateTimeField(auto_now_add=True)
    

    现在您可以按如下方式过滤最低价格,

    qs = [p for p in Product.objects.all() if p.current_price]
    # Returns a list of products that have a current price
    
    # To get the lowest price,
    cheapest_product = min(qs, key=lambda x: x.current_price)
    cheapest_product.current_price
    
    # To get the highest price,
    most_expensive_product = max(qs, key=lambda x: x.current_price)
    most_expensive_product.current_price
    

    您可以让模型经理为您执行此操作,请参阅django docs 了解更多信息。

    最好你想要一个可以像这样工作的经理,

    Product.objects.cheapest()  # returns the single cheapest 'current' price.
    Product.objects.most_expensive()  #returns most expensive (highest) price
    

    【讨论】:

    • 谢谢......但我真的想要一种方法,而不需要在 Product 模型上创建额外的字段,但如果这是唯一的方法,那么我必须这样做。!
    • 此解决方案没有创建额外的字段。 @property 方法不会创建数据库字段。还是我误会了你?
    • 如果你指的是@property/'current_price',这只是一个帮助你处理模型的python函数,数据库没有被触及..
    • Arhhh ...对不起,现在我明白了..完美,我会尝试一下..我认为这正是我所需要的..很好..谢谢!
    • 没问题!祝你好运
    【解决方案2】:

    这应该可以解决问题。

    from django.db.models import Max
    
    prods_with_prices = []
    for prod in Product.objects.all():
        prices = Prices.objects.filter(product = prod).annotate(current_price=Max('created'))
        prods_with_prices.append({'product': prod, 'price': prices.current_price})
    costly_prod = max(prods_with_prices, key = lambda x: x['price'])['product']
    cheap_prod = min(prods_with_prices, key = lambda x: x.['price'])['product']
    
    print "Most expensive product: " + costly_prod
    print "Least expensive product: " + cheap_prod
    

    【讨论】:

    • @pkdkk 刚刚编辑,因为我的第一个答案有错误。让我知道这是否适合您。
    猜你喜欢
    • 2016-01-26
    • 2021-11-04
    • 2018-10-12
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    相关资源
    最近更新 更多