问题
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