【发布时间】:2019-08-19 13:09:46
【问题描述】:
我正在制作某种价目表,价格会随着时间而变化。 我在检索每种产品的最新价格时遇到问题。
我的模型如下:
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
class Product(models.Model):
id = models.PositiveIntegerField(primary_key=True, validators=[MinValueValidator(10000), MaxValueValidator(99999)])
name = models.CharField(max_length=100, null=False, blank=False)
def __str__(self):
return f'[{self.id}] {self.name}'
class ProductPart(models.Model):
product = models.ForeignKey('Product', on_delete=models.CASCADE, null=False)
price = models.DecimalField(decimal_places=2, max_digits=7, null=False)
date_created = models.DateTimeField(auto_now_add=True)
date_changed = models.DateTimeField(auto_now=True)
我有一个原始的 SQL 变体,但不知道如何将其转换为 Django 查询。
原始查询是:
select
pp.id as product_id,
pp.name as product_name,
ppp.price as price
from
pricelist_Product as pp
inner join pricelist_ProductPart as ppp
on pp.id=ppp.product_id
where
(pp.id, ppp.id) in
(
select
pp.product_id,
max(pp.id)
from
pricelist_ProductPart as pp
group by
pp.product_id
)
请帮帮我。
【问题讨论】: