Answer the question
In order to leave comments, you need to log in
How to simplify the request to get the latest chats?
Hello to all! Looking at my old retrieve-a method of recent chats with users. This is complete trash, since several queries are made to the database, and two more cycles.
chatters = []
for message in Message.objects.filter(Q(user_from=user)|Q(user_to=user))\
.order_by("created"):
chatters.append(message.user_from)
chatters.append(message.user_to)
counter = Counter(chain(chatters))
ordered = sorted(
set(chatters).union(chatters),
key=lambda k: counter[k],
reverse=True)
chatters=[]
for chatter in ordered:
chatters.append(
Message.objects.filter(
Q(user_from=chatter,user_to=user)|Q(user_from=user,user_to=chatter))\
.order_by("-created")[0])
chats = sorted(set(chatters),key=lambda k: k.created,reverse=True)
chats = []
messages = Message.objects.filter(Q(user_from=user)|Q(user_to=user)).order_by("created")
chatters = set(messages.values_list('user_from', flat=True)).union(messages.values_list('user_to', flat=True))
for chatter in list(chain(chatters)):
filtered = messages.filter(Q(user_from__id=chatter,user_to=user)|Q(user_from=user,user_to__id=chatter)).order_by("-created")
if len(filtered)>0:
chats.append(filtered[0])
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question