Remove all ForeignKey references from model __str__ methods #2158

Closed
opened 2025-12-29 17:22:48 +01:00 by adam · 0 comments
Owner

Originally created by @jeremystretch on GitHub (Nov 28, 2018).

Proposed Changes

There are some instances where the __str__() method of a model references a field on a related model. For example:

class Circuit(ChangeLoggedModel, CustomFieldModel):
    ...
    def __str__(self):
        return '{} {}'.format(self.provider, self.cid)

We should rewrite these methods to ensure that they only reference local properties.

Justification

This is inefficient as it generates a database query for the lookup, unless care was taken to include the related field in the queryset used to retrieve the instance(s). Additionally, it can trigger a RelatedObjectDoesNotExist exception when attempting to print the model class (see #2623).

Originally created by @jeremystretch on GitHub (Nov 28, 2018). ### Proposed Changes There are some instances where the `__str__()` method of a model references a field on a related model. For example: ``` class Circuit(ChangeLoggedModel, CustomFieldModel): ... def __str__(self): return '{} {}'.format(self.provider, self.cid) ``` We should rewrite these methods to ensure that they only reference local properties. ### Justification This is inefficient as it generates a database query for the lookup, unless care was taken to include the related field in the queryset used to retrieve the instance(s). Additionally, it can trigger a `RelatedObjectDoesNotExist` exception when attempting to print the model class (see #2623).
adam closed this issue 2025-12-29 17:22:48 +01:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/netbox#2158