首页 > 解决方案 > 如何在 Django 中进行此查询?

问题描述

我有这些字段(test_type, status, begin_time, and_time)。该status字段具有三个状态(012。我想做一个查询集,其中:

(test_type = 'difficult') and 
(if status=1 and begin_time + 2x(end_time - begin_time) < timezone.now()) or
(if status=2 and end_time < timezone.now()) 

然后选择这些字段。如果状态 state=0 我不想选择该字段。如何使用 Django ORM 制作这个查询集?

标签: pythondjangodjango-queryset

解决方案


您将不得不在 Django 中使用 Q 对象,

Model.objects.filter((Q(status=1) & Q(begin_time < computed_value_here)) | (Q(status=2) & Q(end_time < computed_value_here)), test_type='difficult')

推荐阅读