gpt4 book ai didi

sql - Django 复杂的过滤器和顺序

转载 作者:行者123 更新时间:2023-11-29 11:29:14 24 4
gpt4 key购买 nike

我有4个这样的模型

class Site(models.Model):
name = models.CharField(max_length=200)

def get_lowest_price(self, mm_date):
'''This method returns lowest product price on a site at a particular date'''

class Category(models.Model):
name = models.CharField(max_length=200)
site = models.ForeignKey(Site)

class Product(models.Model):
name = models.CharField(max_length=200)
category = models.ForeignKey(Category)

class Price(models.Model):
date = models.DateField()
price = models.IntegerField()
product = models.ForeignKey(Product)

这里每一个都有很多分类,每个分类有很多产品。现在产品价格每天都在变化,因此价格模型将保存产品价格和日期。

我的问题是我想要按价格范围过滤的网站列表。这个价格范围将取决于 get_lowest_price 方法,可以从 Min 到 Max 和 Max 到 Min 排序。我已经使用 lambda 表达式来做到这一点,但我认为这不合适

sorted(Site.objects.all(), key=lambda x: x.get_lowest_price(the_date))

我也可以通过运行一个循环来获得价格范围内的所有网站,但这也不是一个好主意。请帮助我的人以正确的方式进行查询。

如果您仍然需要更清楚地了解问题,请参阅“Ishtiaque Khan”的第一条评论,他的假设是 100% 正确的。

*在这些模型中,写入频率较低,读取频率较高。

最佳答案

<强>1。使用查询
如果您只想使用特定日期进行查询。方法如下:

q = Site.objects.filter(category__product__price__date=mm_date) \
.annotate(min_price=Min('category__product__price__price')) \
.filter(min_price__gte=min_price, min_price__lte=max_price)

它将返回 mm_date 价格在 min_price - max_price 范围内的网站列表。您还可以使用如下查询查询多个日期:

q = Site.objects.values('name', 'category__product__price__date') \
.annotate(min_price=Min('category__product__price__price')) \
.filter(min_price__gte=min_price, min_price__lte=max_price)

<强>2。 Eager/pre-calculation,可以使用post_save信号。由于写入频率低,这不会很昂贵

  • 创建另一个 以保存每个日期的最低价格。像这样:
    class LowestPrice(models.Model):
date = models.DateField()
site = models.ForeignKey(Site)
lowest_price = models.IntegerField(default=0)
  • 每次都使用post_save 信号进行计算和更新。示例代码(未测试)
    from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Price)
def update_price(sender, instance, **kwargs):
cur_price = LowestPrice.objects.filter(site=instance.product.category.site, date=instance.date).first()
if not cur_price:
new_price = LowestPrice()
new_price.site = instance.product.category.site
new_price.date = instance.date
else:
new_price = cur_price
# update price only if needed
if instance.price<new_price.lowest_price:
new_price.lowest_price = instance.price
new_price.save()
  • 然后在需要的时候直接从这个表中查询即可:
    LowestPrice.objects.filter(date=mm_date, lowest_price__gte=min_price, lowest_price__lte=max_price)

关于sql - Django 复杂的过滤器和顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45584433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com