我有以下型号:
class Product_shipment(models.Model):
product_dscr = models.ForeignKey(Product_dscr, related_name='product_dscr', on_delete=models.CASCADE)
import_date = models.DateTimeField(auto_now=True)
stock = models.PositiveIntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
我需要创建一个具有唯一 product_dscr 的对象。应根据 import_date 的最小值选择重复项。以下SQL代码工作正常:
select id, import_date, stock, product_dscr_id
from shop_product_shipment
where import_date = (
select min(import_date)
from shop_product_shipment as s
where s.product_dscr_id = shop_product_shipment.product_dscr_id);
任何人都可以在Django中翻译如何翻译吗?
答案 0 :(得分:0)
以下条目诀窍:
min_val = Product_shipment.objects.order_by('product_dscr').values('product_dscr').annotate(Min('id'))
out = Product_shipment.objects.filter(id__in=min_val.values_list('id__min', flat=True))