从最接近日期,Django模型的对象获取标题

时间:2019-01-23 08:21:56

标签: django django-rest-framework

我要模特:
周:

class Week(models.Model):
    week_id = models.Charfield(unique=True, null=False, primary_key=True)
    year = models.PositiveSmallInteger()
    weeknumber = models.PositiveSmallInteger()
    ...


最后期限

class Deadline(models.Model):
    deadline_type = models.CharField()
    end_at = models.DateTimeField(blank=False)
    week_id  = models.ForeignKey(Week, related_name='deadlines', on_delete=models.CASCADE)
   ...

哪个给我的输出像:

{
    "weeknumber": 1,
    "leaflet_year": 2019,
    "week_id": "01_2019",
    "deadlines": [
        {
            "deadline_type": "Some Deadline type",
            "end_at": "2019-10-23T14:00:00Z",
        },
    ...
    ]
}

我要实现的是用截止日期deadline_type最接近今天的end_at注释Week对象。

我可以注释结束日期,但是我根本不知道如何获取类型。

1 个答案:

答案 0 :(得分:0)

我认为您可以使用subquery这样:

from django.models.db import Subquery, OuterRef


deadline = Deadline.objects.filter(week_id=OuterRef('pk')).order_by('end_at')

weeks = Week.objects.all().annotate(closest_deadline_type=Subquery(deadline.values('deadline_type')[:1]))