[Answered ]-Django: Setting def __str__ to a Related Model

1👍

The reason this happens is because inspector is a ForeignKey. This means that an Inspector can have zero, one, or more related Profiles, and this also means that self.inspector_profile is not a Profile object, but a RelatedObjectManager that manages Profile objects. You can for example print all the related Profile names with:

class Inspector(BaseModel):
    # …
    
    def __str__(self):
        profiles = [str(profile) for profile in self.inspector_profile.all()]
        return f'{" ".join(profiles)} {self.inspector_number}'

But probably the main question is if an Inspector should be related to potentially multiple Profiles, and that the relation should not be a OneToOneField from Inspector to Profile.

Leave a comment