Why is related_name required for annotation?
I'm struggling to understand why related_name
is required in order to do annotation.
When trying to obtain the count of related object as annotation, one could use the below:
class ModelA(models.Model):
(...)
class ModelB(models.Model):
model_a_fk = models.ForeignKey(ModelA, related_name="model_bs")
ModelA.objects.annotate(num_model_b=Count('model_bs')).order_by('-num_model_b')
Why is the related_name
required on the model and can't we just use the below?
ModelA.objects.annotate(num_model_b=Count('model_a_fk_set')).order_by('-num_model_b')
As this yields following error:
FieldError: Cannot resolve keyword 'model_a_fk_set' into field. Choices are: id, (...)