【问题标题】:DISTINCT ON fields is not supported by this database backend此数据库后端不支持 DISTINCT ON 字段
【发布时间】:2019-06-12 10:13:15
【问题描述】:

我正在使用 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

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

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

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()

【问题讨论】:

  • 你使用什么数据库?
  • @SergeyPugach 我正在使用 MySQL。
  • 它不适用于 MySQL,它仅适用于 PostgreSQL。

标签: django django-models django-forms django-templates django-views


【解决方案1】:

distinct('field_name') 在 MySQL 中不受支持。它只支持distinct()distinct('field_name') 仅适用于 PostgresSQL。更多详情请查看documentation

示例(第一个之后的示例仅适用于 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')
   [...]

【讨论】:

【解决方案2】:

愿你应该这个

>>> queryset = TimesheetEntry.objects.distinct()
>>> context['reports'] = queryset .filter(timesheet_jobs__job_company = self.request.user.userprofile.user_company, )

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 2020-05-01
    • 2015-04-13
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2016-09-05
    相关资源
    最近更新 更多