关联字段查询
_exam_fields = ['add_datetime', 'times', 'start_date', 'end_date', 'uuid', 'name', 'img', 'duration',
'bx_duration']
_alias_fields = {
'pass_score': F('score'), 'exam_paper_id': F('exam_paper__uuid'),
'exam_paper_name': F('exam_paper__name'),
'again_uuid': Value('', output_field=CharField())
}
_exam__filter = {'exam_range__org__org_user__user_id': self.request.user_id}
query_exam = Exam.objects.filter(**_exam__filter).values(*_exam_fields).annotate(**_alias_fields).order_by(
'-add_datetime')
_again_fields = ['add_datetime', 'times', 'start_date', 'end_date', ]
_alias_fields = {
'uuid': Value('', output_field=CharField()), 'name': F('exam__name'), 'img': F('exam__img'),
'duration': F('exam__duration'), 'bx_duration': F('exam__bx_duration'), 'pass_score': F('exam__score'),
'exam_paper_id': F('exam__exam_paper__uuid'), 'exam_paper_name': F('exam__exam_paper__name'),
'again_uuid': F('uuid'),
}
使用关联字段更新
UserCert.objects.filter(
exam_record__is_pass=True,
status=1
).update(
user=Subquery(
ExamRecord.objects.filter(
uuid=OuterRef('exam_record_id'),
is_pass=True
).values('user')[:1]
),
status=2
)
使用子查询过滤
subquery = MockExamRecord.objects.filter(
mock_exam_id=OuterRef('mock_exam_id'),
user_id=self.request.user_id,
).order_by('-add_datetime').values('add_datetime')[:1]
obj_list = MockExamRecord.objects.filter(
add_datetime__in=Subquery(subquery),
user_id=self.request.user_id,
).distinct('mock_exam_id')
标签:__,exam,查询,paper,orm,user,django,id,uuid
From: https://www.cnblogs.com/guanchaoguo/p/17593694.html