简体   繁体   中英

Django select related with max field value for each result

I have two models.

models.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 ).

views.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 ?

If you set a foreign key relation in 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. You can order_by('-date') to reverse the order

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM