سؤال

I have the following model:

class CarPrice(models.Model):
    car = models.ForeignKey(Car)
    price = models.ForeignKey(Price)
    start_date = models.DateTimeField(default=datetime.datetime.now())

There can be multiple CarPrices for the same Car with different start_dates for the set price.

I need something that looks like:

car_prices = CarPrice.objects.filter(car__in=cars).get_latest()

How can I construct a query that returns a QuerySet with all the latest CarPrices (start_date < now) for each Car in cars (needs to be distinct for each car).

هل كانت مفيدة؟

المحلول

from django.db.models import Max, F

car_prices = CarPrice.objects.filter(car__in=cars) \
    .annotate(latest=Max('car__carprice_set__start_date')) \
    .filter(start_date=F('latest'))

This will annotate each CarPrice object with the latest start_date for all prices related to the CarPrice's car. Filtering on start_date=F('latest') will return only the latest object for each Car.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top