G
G
Glitchmorphosis2019-10-26 15:34:12
Django
Glitchmorphosis, 2019-10-26 15:34:12

How to execute aggregate function in prefetch_related?

Here are the models:

class ObjectDataAdditional(models.Model):
    percentage_technical_readiness = models.FloatField(
        null=True,
    )
    #какие-то поля


class ObjectDataNormalized(models.Model):
    #какие-то поля


class NormalizedAdditional(models.Model):
    normalized_object = models.ForeignKey(
        ObjectDataNormalized,
        on_delete=models.CASCADE,
        null=True,
        related_name='normal_object',
    )
    additional_object = models.ForeignKey(
        ObjectDataAdditional,
        on_delete=models.CASCADE,
        related_name='additional_object',
        null=True,
    )


class LinkedData(models.Model):
    many = models.ManyToManyField(
        ObjectDataNormalized,
        related_name='many_related',
    )


class LinkedInfo(models.Model):
    linked_data = models.ForeignKey(
        LinkedData,
        on_delete=models.CASCADE,
        related_name='linked_data_related'
    )
    normalized = models.ForeignKey(
        ObjectDataNormalized,
        on_delete=models.CASCADE,
        related_name='normalized_related'
    )
    main = models.BooleanField(
        default=False,
        null=False,
    )

One object ObjectDataNormalizedcan have several ObjectDataAdditional. All binding goes to NormalizedAdditional.
I need to get data from all listed tables. This is how I am trying to do it:
prefetch = Prefetch('normalized__normal_object',  queryset=NormalizedAdditional.objects.
annotate(max_percentage=Max('additional_object__percentage_technical_readiness')))

info = LinkedInfo.objects.all().order_by('linked_data_id',
                                                 '-main').select_related(
            'linked_data',
            'normalized',
        ).prefetch_related(prefetch)

Everything seems to be working. From infoI can pull out data from LinkedInfo, linked_data, normalizedbut I cannot get the value percentage_technical_readiness. A lot of how I tried to pull this value out actually.
That is, in a table NormalizedAdditional, one object normalized_objectcan have several ObjectDataAdditional:
normalized_object_id	additional_object_id
8	                                6580
8	                                6579
9	                                11006
9	                                10999

And I need to pull the maximum value percentage_technical_readinessfor the normalized_object. The field percentage_technical_readinessis in the table ObjectDataAdditional.
Or maybe Django ORM is not suitable for such complex queries? Can in such cases it is better to use stored procedures?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2019-10-28
@Glitchmorphosis

Try Prefetch(qs)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question