我有以下型号。
class Product(models.Model):
title = models.CharField(max_length=500)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Price(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
amount = models.DecimalField(decimal_places=2, max_digits=6)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
基本上我想跟踪产品的价格。 每个产品都有一个当前价格,并且可能有以前的价格历史记录。
我需要很多东西。
我需要有价格的产品,但按价格订购。
我做了以下事情。
queryset = Product.objects.all()
queryset = queryset.prefetch_related(
Prefetch("price_set", queryset=Price.objects.all())
)
queryset = queryset.order_by("price__amount")
这是正确的吗?或者有更有效的方法吗?
我需要按价格变化次数对产品进行排序。 例如,如果产品 A 的价格在过去 10 天内更改了 5 次,产品 B 的价格在过去 10 天内更改了 6 次,那么在查询集中,产品 B 应该是第一个,产品 A 应该是第二个?
我不知道该怎么做。
请帮我解答这两个问题。任何帮助将不胜感激。谢谢你。
我尝试过的就是上面的。
您可以通过添加指定时间范围内的相关价格变化,然后根据此计数对查询集进行排序来实现此目的。
from django.db.models import Count, Q
from datetime import timedelta
time_frame = timezone.now() - timedelta(days=10)
queryset = Product.objects.annotate(
price_changes_count=Count(
"price",
filter=Q(price__timestamp__gte=time_frame)
)
)
queryset = queryset.order_by("-price_changes_count")