AttributeError: 'list' object has no attribute 'order_by'

六月ゝ 毕业季﹏ 提交于 2021-01-29 08:11:14

问题


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


回答1:


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

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.



来源:https://stackoverflow.com/questions/64985718/attributeerror-list-object-has-no-attribute-order-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!