条件为真时相关 Django 模型的最大列值
Max column value of related django model where condition is true
TAssignment 模型有许多与 TSlot 模型相关的条目,例如 1 pk 的 TSlot 模型,TAssignment model.Now 中有许多条目,此查询输出来自 Tslot table 的值以及最新创建的相关信息和更新自 Tassignment table.But 我想要的是最新值
'assignment_Slot__created_on' 和 'assignment_Slot__updated_on' 当 assignment_Slot__is_deleted=False。
问题:如何在注释中添加“assignment_Slot__is_deleted=False”条件以及 'assignment_Slot__created_on' 和 'assignment_Slot__updated_on' 而不会重复结果。
** assignment_Slot 这里是相关名称
TSlot.objects.filter(request__id=request_id, is_deleted=False
).values("slot_date", "type_of_work", "reason_for_less_assign", "request_id","slot", "remarks",
slot_id=F("id"), request_status=F('request__request_status')).annotate(
assigned_on=Max('assignment_Slot__created_on'), modified_on =Max('assignment_Slot__modified_on'))
添加一个filter to your annotations, see filtering on annotations
from django.db.models import Max, Q, DateField
TSlot.objects.filter(...).annotate(
assigned_on=Max('assignment_Slot__created_on', filter=Q(assignment_Slot__is_deleted=False), output_field=DateField()),
modified_on=Max('assignment_Slot__modified_on', filter=Q(assignment_Slot__is_deleted=False), output_field=DateField())
)
TAssignment 模型有许多与 TSlot 模型相关的条目,例如 1 pk 的 TSlot 模型,TAssignment model.Now 中有许多条目,此查询输出来自 Tslot table 的值以及最新创建的相关信息和更新自 Tassignment table.But 我想要的是最新值 'assignment_Slot__created_on' 和 'assignment_Slot__updated_on' 当 assignment_Slot__is_deleted=False。
问题:如何在注释中添加“assignment_Slot__is_deleted=False”条件以及 'assignment_Slot__created_on' 和 'assignment_Slot__updated_on' 而不会重复结果。
** assignment_Slot 这里是相关名称
TSlot.objects.filter(request__id=request_id, is_deleted=False
).values("slot_date", "type_of_work", "reason_for_less_assign", "request_id","slot", "remarks",
slot_id=F("id"), request_status=F('request__request_status')).annotate(
assigned_on=Max('assignment_Slot__created_on'), modified_on =Max('assignment_Slot__modified_on'))
添加一个filter to your annotations, see filtering on annotations
from django.db.models import Max, Q, DateField
TSlot.objects.filter(...).annotate(
assigned_on=Max('assignment_Slot__created_on', filter=Q(assignment_Slot__is_deleted=False), output_field=DateField()),
modified_on=Max('assignment_Slot__modified_on', filter=Q(assignment_Slot__is_deleted=False), output_field=DateField())
)