Django ORM – 如何获取最大价格和相关的日期

huangapple go评论65阅读模式
英文:

Django ORM - How to get max price and the associated date

问题

以下是您要翻译的内容:

"关注我在杂货店购买的物品价格。
我有以下这些模型:

Class Product(models.Model):
    title = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    information = models.CharField(max_length=255)

Class Price(models.Model):  
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    date_seen = models.DateTimeField(auto_now_add=True)
    price = models.IntegerField(blank=True, null=True)

我尝试为每个产品获取最高价格和相关日期。
如果我执行以下操作:

def get_max_price_for_product(request):
    max_price_list = (
        Price.objects.values("product__title", "product__name")
        .annotate(score=Max("price"))
        .order_by("-price")
    )

    context = {"max_price_list": max_price_list}
    return render(request, "prices/max_list.html", context)

我可以获得每个产品的最高价格,但没有日期信息。我阅读了Django文档,但没有找到(或者我没有理解我所阅读的内容)如何做到这一点。

有人可以帮助我吗?
提前谢谢。"

英文:

To follow the price of what I buy at the grocery.
I have these models :

Class Product(models.Model):
    title = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    information = models.CharField(max_length=255)

Class Price(models.Model):  
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    date_seen = models.DateTimeField(auto_now_add=True)
    price = models.IntegerField(blank=True, null=True)

And I try to have for each product the max price and the associated date.
If I do

def get_max_price_for_product(request):
    max_price_list = (
        Price.objects.values("product__title", "product__name")
        .annotate(score=Max("price"))
        .order_by("-price")
    )

    context = {"max_price_list": max_price_list}
    return render(request, "prices/max_list.html", context)

I've the max price for each product but without the date. I read the Django doc but I didn't find (or I didn't understand what I read) how to do this.

Can somebody help me ?
Thank you in advance.

答案1

得分: 1

以下是翻译好的部分:

可能更好的做法是使用`QuerySet`,`Product`作为主要模型如下所示

```python
from django.db.models import Max

Product.objects.annotate(max_price=Max('price__price'))

这样,您将检索具有额外属性.max_priceProduct对象,但它仍然像Product对象一样运行,因此您可以跟踪ForeignKey等。

您可以通过使用子查询来获取修改日期:

from django.db.models import F, Max, OuterRef, Subquery

def get_max_price_for_product(request):
    Product.objects.annotate(
        max_price=Max('price__price'),
        max_price_date=Subquery(
            Price.objects.filter(product_id=OuterRef('pk'))
            .order_by(F('price').desc(nulls_last=True))
            .values('date_seen')[:1]
        ),
    )
    context = {'max_price_list': max_price_list}
    return render(request, 'prices/max_list.html', context)

这将检索最大价格的date_seen


请注意,`<b>`和`</b>`不是翻译部分,它们是HTML标签,用于加粗文本。

<details>
<summary>英文:</summary>

It might be better to work with a `QuerySet` with `Product` as the main model, so:

&lt;pre&gt;&lt;code&gt;from django.db.models import Max

Product.objects.annotate(&lt;b&gt;max_price=Max(&#39;price__price&#39;)&lt;/b&gt;)&lt;/code&gt;&lt;/pre&gt;

that way you retrieve `Product` objects with an extra attribute `.max_price`, but it still functions like a `Product` object, so you can follow `ForeignKey`s, etc.

You can obtain the modification date by using a subquery:

&lt;pre&gt;&lt;code&gt;from django.db.models import F, Max, OuterRef, Subquery


def get_max_price_for_product(request):
    Product.objects.annotate(
        max_price=Max(&#39;price__price&#39;),
        max_price_date=&lt;b&gt;Subquery(&lt;/b&gt;
            Price.objects.filter(product_id=OuterRef(&#39;pk&#39;))
            .order_by(F(&#39;price&#39;).desc(nulls_last=True))
            .values(&#39;date_seen&#39;)[:1]
        &lt;b&gt;)&lt;/b&gt;,
    )
    context = {&#39;max_price_list&#39;: max_price_list}
    return render(request, &#39;prices/max_list.html&#39;, context)&lt;/code&gt;&lt;/pre&gt;

This will retrieve the `date_seen` for the largest price.

</details>



huangapple
  • 本文由 发表于 2023年5月22日 01:33:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76301137.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定