AttributeError:“列表"对象没有属性"order_by" [英] AttributeError: 'list' object has no attribute 'order_by'

查看:58
本文介绍了AttributeError:“列表"对象没有属性"order_by"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过 itertools链 python预定义功能组合两个 queryset 对象,并使用 order_by 对其进行过滤.但是我得到一个 AttributeError :'list'对象没有属性'order_by'.
如果有人能弄清楚我在哪里做错了,那将不胜感激.提前非常感谢您.

I was trying to combine two queryset objects by itertools chain python predefine function and filter this with order_by. but i'm getting an AttributeError: 'list' object has no attribute 'order_by'.
If anybody could figure out where i'm doing thing wrong then would be much appreciated. thank you so much in advance.

views.py:

try:
    qs = Conversation.objects.filter(
        Q(chat__from_user=user) &
        Q(chat__to_user=to_user))

    qs_2 = Conversation.objects.filter(
        Q(chat__from_user=to_user) &
        Q(chat__to_user=user))
except:
    raise ValidationError({"message":"bad request"})

all_qs = list(chain(qs, qs_2)).order_by('-created_on')

推荐答案

您不能 .order_by(…)列表.但是您实际上实际上并不需要此.您可以简单地合并"这两个查询集,并可以使用:

You can not .order_by(…) a list. But you actually do not need this anyway. You can simply "merge" the two querysets, and work with:

from django.db.models import Q

all_qs = Conversation.objects.filter(
        Q(chat__from_user=user, chat__to_user=to_user) |
        Q(chat__from_user=to_user, chat__to_user=user)
).order_by('-created_on')

根据经验,最好避免使用列表,因为即使您设法在Django/Python级别对列表进行排序,它的效率也通常不如数据库级别(系统)旨在有效地完成这些事情.

As a rule of thumb, it is better to avoid lists as much as possible, since even if you manage to sort these at the Django/Python level, it is often less efficient than on the database level, which is a system that is designed to do these things efficiently.

这篇关于AttributeError:“列表"对象没有属性"order_by"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆