Q
Q
Quickaxe-Martina2020-10-14 15:37:34
Django
Quickaxe-Martina, 2020-10-14 15:37:34

How to make a second request in annotate?

Good afternoon, there was a need to add a field to the output of a get request

def annotate_poll_name(self, obj):
        steps = Step.objects.filter(block=obj).annotate(
            poll_text=Poll.objects.get(id=447).text
        )
        return StepSerializer(steps, many=True).data

id is so far specified by hand just for tests, in the future the Step.object_id field should be passed there, the problem is that even in this option everything falls down and I can’t understand why, please help TypeError: QuerySet.annotate() received non-expression( s):
class Step(models.Model):

    STEP_TYPE = (
        ('poll', 'Опрос'),
        ('questions', 'Вопросы'),
        ('file', 'Файл')
    )
    type = models.CharField(
        max_length=60,
        choices=STEP_TYPE
    )
    object_id = models.IntegerField(null=True)
    block = models.ForeignKey(Block, on_delete=models.CASCADE, related_name='steps')
    sort_order = models.PositiveIntegerField(default=1,  validators=[MinValueValidator(1)])

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
noremorse_ru, 2020-10-14
@noremorse_ru

Ebushki are sparrows. Instead of object_id, make the poll = models.ForeignKey(Poll, ***) field, now you can access the associated object as you like, you can make a property and it will automatically fall into the serializer if it is a subclass of ModelSerializer (but this is not accurate, you need to check)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question