Как отфильтровать набор запросов по последнему полю даты с помощью Django?

У меня есть следующая модель, в которой я хочу выполнить запрос для извлечения строк с самой последней датой created_at, заданной списком имен, упорядоченных по самой последней дате вступления в силу:

class Foo(models.Model):
    name = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    effective_date = models.DateField()

Например, данные могут быть следующими:

name  | created_at | effective_date
==================================
testA | 2022-01-01 | 2021-01-01
----------------------------------
testA | 2022-02-01 | 2021-01-01 <--- pick this row since it has the most recent created_at
----------------------------------
testA | 2022-01-01 | 2021-02-01
----------------------------------
testA | 2022-02-01 | 2021-02-01 <--- pick this row since it has the most recent created_at
----------------------------------
testB | 2022-01-01 | 2021-02-01
----------------------------------
testB | 2022-02-01 | 2021-02-01 <--- pick this row since it has the most recent created_at
----------------------------------

Тогда, учитывая names = ['testA', 'testB'], я хочу получить следующие результаты:

name  | created_at | effective_date
==================================
testA | 2022-02-01 | 2021-02-01
----------------------------------
testA | 2022-02-01 | 2021-01-01
----------------------------------
testB | 2022-02-01 | 2021-02-01
----------------------------------

На данный момент я попробовал следующие запросы:

names = ['testA', 'testB']

# This doesn't isolate the rows with the most recent created_by date
queryA = Foo.objects.filter(name__in=names).order_by("-effective_date")

# This returns a single Foo object rather than a list of them as expected
queryB = Foo.objects.filter(name__in=names).order_by("-effective_date").latest("created_at")

Как я могу достичь этого с помощью Django? Я что-то упускаю?

в models.py, вы можете добавить класс Meta и фильтрацию там:

class Foo(models.Model):
    name = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    effective_date = models.DateField()

    class Meta():
            ordering = ['-created_at', '-effective_date']
      
Вернуться на верх