N
N
Neoliz2016-09-05 10:18:39
Django
Neoliz, 2016-09-05 10:18:39

How to properly attach annotation to queryset?

There are models:

class answer(models.Model):
    name = models.CharFIeld("Name", max_length=10)

class message(models.Model):
    message = models.CharField("Message", max_length=50)
    look = models.BooleanField(default=False)
    answer = models.ForeignKey(answer)

And I need to get the queryset 'answer' set and attach two Boolean content attributes to each object: If there is
message(look=False, answer=(к текущему объекту итерции answer)) то True  Иначе False

And the number of related messages for each answer
is done with crutches (let's say the future field is called look_bool, new_bool):
for item in answer.objects.all():  # filter(...)
    messages_ = message.objects.filter(answer=item)
    if messages_ .count():
        item.look_bool= True 
    else:
        item.look_bool= False
    if messages_ .filter(view=False).count():
        item.new_bool= True 
    else:
        item.new_bool= False

And how to do it right without a bunch of requests? Maybe there is some elegant solution, or tell me where to smoke. About a bunch of requests, I mean (because for each object answer makes a full-fledged request) messages_ = message.objects.filter(answer=item)
PS Maybe I'm not looking at the task that way. Required for further transfer to the set template(
django.views.generic.ListView
), and there, if True, display an additional field for answer.
Found to dock, but did not understand up to the end. https://docs.djangoproject.com/en/dev/topics/db/ag... Here
is an example of my code that doesn't work the way I want:
answ = answer.objects.all()  # filter(...)
answ.annotate(
            count_message=Count('message')
        ).annotate(
        new_message=Count('message')
        ).filter(
        message__look=False
    )

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question