Objective: I am trying to set the __str__ of a model to the name of a related model. The Profile model has a __str__ that returns "last name, first name" of the user. I would like the Inspector to return something similar with their inspector_number.
Currently: The __str__ is returning "users.Profile.None 12345" instead of the desired "Doe, John 12345".
This is one of my first times using related_name for a model and I seem to be missing something.
Model.py
class Profile(BaseModel):
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, blank=True)
inspector = models.ForeignKey(Inspector, on_delete=models.SET_NULL, null=True, blank=True, related_name="inspector_profile")
def __str__(self):
return self.user.last_name + ", " + self.user.first_name
class Inspector(BaseModel):
...
inspector_number = models.CharField(max_length=19, unique=True, editable=False, default=get_inspector_number)
def __str__(self):
ret = str(self.inspector_profile) + " " + str(self.inspector_number)
return ret
Update:
I was able to solve the issue by using if hasattr(self, 'inspector_profile'):. All of the records had the attribute but this seemed to correct my issue.
The reason this happens is because
inspectoris aForeignKey. This means that anInspectorcan have zero, one, or more relatedProfiles, and this also means thatself.inspector_profileis not aProfileobject, but aRelatedObjectManagerthat managesProfileobjects. You can for example print all the relatedProfilenames with:But probably the main question is if an
Inspectorshould be related to potentially multipleProfiles, and that the relation should not be aOneToOneFieldfromInspectortoProfile.