pythondjangodjango-models

Difference between 'related_name' and 'related_query_name' attributes in Django?


Can you explain the difference between related_name and related_query_name attributes for the Field object in Django ? When I use them, How to use them? Thanks!


Solution

  • related_name will be the attribute of the related object that allows you to go 'backwards' to the model with the foreign key on it. For example, if ModelA has a field like: model_b = ForeignKeyField(ModelB, related_name='model_as'), this would enable you to access the ModelA instances that are related to your ModelB instance by going model_b_instance.model_as.all(). Note that this is generally written with a plural for a Foreign Key, because a foreign key is a one to many relationship, and the many side of that equation is the model with the Foreign Key field declared on it.

    The further explanation linked to in the docs is helpful. https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects

    related_query_name is for use in Django querysets. It allows you to filter on the reverse relationship of a foreign key related field. To continue our example - having a field on Model A like: model_b = ForeignKeyField(ModelB, related_query_name='model_a') would enable you to use model_a as a lookup parameter in a queryset, like: ModelB.objects.filter(model_a=whatever). It is more common to use a singular form for the related_query_name. As the docs say, it isn't necessary to specify both (or either of) related_name and related_query_name. Django has sensible defaults.