事务
1 2 3 4 5 6 7 8 9 10 11 12
| correction = Correction.objects.get(id=self.kwargs.get('pk')) correction.correct_at = timezone.now() correction.correct_user_id = self.request.user.id with transaction.atomic(): correction.save() Inbox.objects.new_notify( user_id=correction.report_user.id, title=f"#{self.kwargs.get('pk')} 纠错已处理", content=f"<p>您的错误反馈 #{self.kwargs.get('pk')} 已处理 </p>" f"<p>点击<a href='/tk/question/{correction.question.id}'>这里</a>查看对应的题目</p>", extra_type=Inbox.EXTRA_PLATFORM )
|
1 2 3 4 5 6 7 8 9 10 11
| qs.values('a') QS<{a:b},{a:c} >
qs.values_list('a') QS<(b,), (c,)>
qs.values_list('a', flat=True) QS<[b, c]>
|
1 2 3 4 5 6 7 8 9 10
| def get_queryset(self): _filter = self.request.GET.get('filter', 'dashboard') if _filter == 'dashboard': qs = School.objects.filter(is_active=True).exclude(id__in=settings.DASHBOARD_EXCLUDE_SITES) if site_ids := settings.STATIS_USER_SITE.get(self.request.user.id): qs = qs.filter(id__in=site_ids) else: qs = School.objects.filter(is_active=True).order_by('site_title') return qs
|
上面的代码本来不会出问题的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| def get_queryset(self): _filter = self.request.GET.get('filter', 'dashboard') user_id = self.request.user.id if _filter == 'dashboard': if self.request.user.username == 'fljy': qs = School.objects.filter(is_active=True).exclude( id__in=settings.DASHBOARD_EXCLUDE_SITES ) else: qs = OperatorSchool.objects.filter( user_id=user_id, school__is_active=True ) else: qs = School.objects.filter(is_active=True).order_by('site_title') return qs
|
结果因为加了一个用户只能查看他所管理的学校之后,就出bug了,我发现原因是qs不在是School模型的queryset,而是变成OperatorSchool了。
1 2 3 4 5 6 7 8 9 10
| class OperatorSchool(BaseModel): """ 后台管理: 运营管理的学校 since: 21.6.16 """ user = models.ForeignKey(User, verbose_name='运营', db_index=False, on_delete=CASCADE) school = models.ForeignKey('market.School', verbose_name='负责学校', db_index=False, on_delete=CASCADE)
class Meta: unique_together = (('user', 'school'),)
|
以上是他的模型定义。我应该如何将else分支里的内容转化为School?
1 2 3 4 5
| school_ids = OperatorSchool.objects.filter( user_id=user_id, school__is_active=True ).values_list('school_id', flat=True) qs = School.objects.filter(id__in=school_ids)
|
进一步优化成一个语句
1 2 3 4
| qs = School.objects.filter( operatorschool__user_id=user_id, operatorschool__school__is_active=True ).distinct()
|
双杠优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
max_percent = PaperClassQuestionPercent.objects.filter( paper_question__paper=task_obj.paper, paper_question__question_id=question.question_id ).order_by('-correct_percent').first().correct_percent
|
python代码尽量不要写函数嵌套,否则影响性能
Author:
Littlefean
License:
Copyright (c) 2019 CC-BY-NC-4.0 LICENSE
Slogan:
仅个人观点,buddy up!