此数据库后端不支持 DISTINCT ON 字段

Aad*_*ikh 10 django django-templates django-models django-forms django-views

我正在使用 distinct 来获取不同的最新值,但它给了我一个错误:

此数据库后端不支持 DISTINCT ON 字段

views.py

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.filter(
                                  timesheet_jobs__job_company = self.request.user.userprofile.user_company,
                              ).distinct('timesheet_users')
        return context
Run Code Online (Sandbox Code Playgroud)

基本上我想查询TimesheetEntry模型,其中会有很多条目userUser内置模型中的外键。

所以我想用不同的用户查询,以便显示用户的最新条目。获取用户的最新条目对我来说非常重要。

models.py

class TimesheetEntry(models.Model):
    timesheet_users = models.ForeignKey(User, on_delete=models.CASCADE,related_name='timesheet_users')
    timesheet_jobs = models.ForeignKey(Jobs, on_delete=models.CASCADE,related_name='timesheet_jobs')
    timesheet_clock_in_date = models.DateField()
    timesheet_clock_in_time = models.TimeField()
Run Code Online (Sandbox Code Playgroud)

rud*_*dra 24

distinct('field_name')MySQL 不支持。它只支持distinct(). distinct('field_name')仅适用于PostgresSQL。有关更多详细信息,请查看文档

实例(与第一只在PostgreSQL上下班后): 复制粘贴的来自文档:

>>> Author.objects.distinct() 
   [...]

>>> Entry.objects.order_by('pub_date').distinct('pub_date')
   [...]

>>> Entry.objects.order_by('blog').distinct('blog')
   [...]

>>> Entry.objects.order_by('author', 'pub_date').distinct('author', 'pub_date')
   [...]

>>> Entry.objects.order_by('blog__name', 'mod_date').distinct('blog__name', 'mod_date')
   [...]

>>> Entry.objects.order_by('author', 'pub_date').distinct('author')
   [...]
Run Code Online (Sandbox Code Playgroud)

  • 你能告诉我如何查询MySQL吗? (2认同)