【问题标题】:Django ORM values() and select_related() raise TypeErrorDjango ORM values() 和 select_related() 引发 TypeError
【发布时间】:2019-01-14 10:07:43
【问题描述】:

在我的 django 项目中,我必须像这样进行 ORM 查询:

ordered = t_threads.objects.values('thread_stag').filter(thread_status='DEAD',id_test__test_main__descr__contains= 'Hello').distinct().select_related().order_by('id')[1:10]

我需要对值“thread_stag”的结果进行分组,过滤状态和测试描述,具有来自相关表的所有值,但是当我执行上述查询系统返回时:

raise TypeError("Cannot call select_related() after .values() or .values_lis t()")

如果我删除“select_related()”选项,我没有相关表中的值。 我怎样才能在 django ORM 中实现我的结果?

提前非常感谢

【问题讨论】:

  • 试试ordered = t_threads.objects.filter(thread_status='DEAD',id_test__test_main__descr__contains= 'Hello').values('thread_stag').order_by('id').distinct()[1:10]
  • 尝试在最后移动值('thread_stag')
  • select_related 不会更改您返回的字段,它只会使关注相关对象更有效。

标签: python django orm


【解决方案1】:

只需将values 移动到末尾,如下所示:

ordered = t_threads.objects \ 
           .filter(thread_status='DEAD',id_test__test_main__descr__contains= 'Hello') \
           .distinct() \ 
           .select_related() \ 
           .values('thread_stag') \ 
           .order_by('id')[1:10]

请注意,您还必须为 select_related 指定字段列表!

【讨论】:

    猜你喜欢
    • 2020-03-21
    • 2017-05-25
    • 2010-12-09
    • 2018-10-23
    • 2015-09-23
    • 2012-10-04
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    相关资源
    最近更新 更多