Trying to reference a str in a difference model class for the self __str__

I couldn’t find anything related to this as I’m not sure what to search for. I’m starting out on a database client list system and I want to reference the clients last name in a separate table. here is my relevant code.

owner = models.ForeignKey('Client', on_delete=models.CASCADE)
def __str__(self):
    return self.name + ' ' + Client(pk='self.owner').lname

it doesn’t throw any errors but it obviously doesn’t work either. I feel like I’m close but I’m not certain.

Your __str__ code is creating a model instance with a primary key of self.owner, then trying to pull some value out of it. Your primary key is likely an integer and that’s not issuing a database query.

What you are looking for is self.owner.lname. I’m assuming that lname is a field on your Client model.

When Django tries to do an attribute access on owner (namely, trying to access lname on the model), it will see that the owner field is a foreign key so it will do a database lookup at that point in time to fetch the associated owner with a database SELECT. After that data is pulled in from the database, it can return the lname attribute value.

1 Like

Thanks that did exactly what I was looking for. I had thought to try that but didn’t ever check if it worked because VS code threw an error. ignoring the error it works perfectly.