我想要一个基于get_params()
的唯一行。但是现在的问题是,它仅在模板中显示timesheet_users
值。即使我在`values('...','...',....)中添加其他字段,然后选择唯一行也不起作用。
我正在使用MySQL,所以我不能使用timesheet_users
-它会给出错误
此数据库后端不支持DISTINCT ON字段
distinct('timsheet_user')
Models.py
TimesheetEntry.objects.filter(
timesheet_jobs__job_company = self.request.user.userprofile.user_company
).values(
'timesheet_users'
).distinct()
答案 0 :(得分:1)
如@AnupYadav建议进行raw
查询。我附带了这个MySQL查询
SELECT * FROM timesheet_entry t1 INNER JOIN ( SELECT timesheet_users_id, MAX(id) AS latest_id FROM timesheet_entry GROUP BY timesheet_users_id ) t2 ON t1.timesheet_users_id = t2.timesheet_users_id AND t1.id = t2.latest_id
这是我使用查询的视图
class ReportView(LoginRequiredMixin, generic.TemplateView):
template_name = 'admin/clock/report.html'
def get_context_data(self, **kwargs):
context = super(ReportView, self).get_context_data(**kwargs)
context['reports'] = TimesheetEntry.objects.raw('SELECT * FROM timesheet_entry t1 INNER JOIN ( SELECT timesheet_users_id, MAX(id) AS latest_id FROM timesheet_entry GROUP BY timesheet_users_id ) t2 ON t1.timesheet_users_id = t2.timesheet_users_id AND t1.id = t2.latest_id')
return context