A
A
Andrey2015-05-08 05:29:27
Django
Andrey, 2015-05-08 05:29:27

Do I need to filter out unnecessary requests in the code?

Hello!
Here is a small piece of code for displaying messages between users:

messages = QuerySet #тут queryset с сообщениями
context['message_list'] = messages

# мне нужно пометить просмотренными сообщения для получателя
# обычно я постоянно делаю запрос на обновление:
Message.objects.filter(recipient=self.request.user, viewed__isnull=True).update(viewed=timezone.now())

# но ведь можно заранее проверить, есть ли новые сообщения и если нужно сделать запрос (вариант 2):
not_viewed_message_ids = [msg.pk for msg in messages if msg.recipient == self.request.user and not viewed]
if not_viewed_message_ids:
    Message.objects.filter(pk__in=not_viewed_message_ids).update(viewed=timezone.now())

What can you say about the second option, is it right to do this or is it not necessary to shift the database tasks to python?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey K, 2015-05-08
@mututunus

Better this way:

if Message.objects.filter(recipient=self.request.user, viewed__isnull=True).exists():
    Message.objects.filter(recipient=self.request.user, viewed__isnull=True).update(viewed=timezone.now())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question