开发者

Django - QuerySet filter - combing 2 conditions

I have a model(Delivery) with 2 fields called name and to_date. I j开发者_Go百科ust need to a object with the specific name and it's maximum to_date.

Delivery.objects.filter(name__exact = 'name1').aggregate(Max('valid_to'))

The above query will return the maximum date. Is it possible to fetch the complete object?


To get a single object ordered by valid_to:

obj = Delivery.objects.filter(name='name1', to_date=my_date).order_by('-valid_to')[0]


Try this:

maximum_to_date = Delivery.objects.filter(name__exact='name1').aggregate(maximum to_date=Max('valid_to'))
result = Delivery.objects.filter(valid_to=maximum_to_date)

Note that you need filter() in the second line, because two or more Deliveries might have the same valid_to value. In such case you can either accept them all, or e.g. take the one with the smallest ID, depending on what you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜