[英]Django select related with max field value for each result
I have two models.我有两个模型。
models.py:模型.py:
class Drink(models.Model):
account = models.ForeignKey(Account, null=False, on_delete=models.CASCADE)
name = models.CharField(max_length=100, null=False, blank=False)
# some other fields that don't matter now...
class DrinkStock(models.Model):
ingredient = models.ForeignKey(Ingredient, null=False, on_delete=models.CASCADE)
quantity = models.DecimalField(max_digits=14, decimal_places=3, null=False, default=0.000)
date = models.DateTimeField(auto_now_add=True)
Let me explain why I have two models before someone post a different solution.让我解释一下为什么在有人发布不同的解决方案之前我有两个模型。 The idea is to have a stock history.这个想法是有一个股票历史。 And when I show all the drinks, I need to display them only with their last related stock
(the one with the latest date
).当我展示所有饮料时,我只需要展示它们的最后一个相关stock
( date
最晚的那个)。
views.py视图.py
def drinks(request):
drinks = Drink.objects.select_related('stock').filter(account__id=request.session['account_id'])
But how can I append the related stock
of each drink
with the lastest date
?但是我怎样才能得到最新date
的每种drink
的相关stock
?
If you set a foreign key relation in DrinkStock:如果您在 DrinkStock 中设置外键关系:
drink = models.ForeigKey(Drink, ... , related_name='drinkstock')
You should be able to iterate the drinks in your view and get the ones with the latest date.您应该能够迭代视图中的饮料并获得日期最晚的饮料。 The code should be similar to:代码应类似于:
def drinks(request):
drinks = Drink.objects.select_related('stock').filter(account__id=request.session['account_id'])
drinks_with_latest_date = [drink.drinkstock.all().order_by('date').first() for drink in drinks]
The drinks_with_latest_date should return the desired result. Drinks_with_latest_date 应该返回所需的结果。 You can order_by('-date') to reverse the order您可以 order_by('-date') 反转顺序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.