Jeet Patel
Jeet Patel

Reputation: 1241

Unable to get Primary Key as a model instance

I have two models Role and User.

When use the object's get() method with the Role model like this -

role= Role.objects.get(pk=1) 

It returns id as an instance of Role like this -

<Role: Role object (2)>

But when I do the same thing with User model like this -

user= User.objects.get(pk=1)

It returns an email as an instance of User model like this -

<User: [email protected]>

How can I make User model return an id as an instance, exactly like Role model.

What exactly will I have to do to achieve this -

<User: User object (2)>

Upvotes: 0

Views: 954

Answers (1)

Jeet Patel
Jeet Patel

Reputation: 1241

My User model was returning user instance which used the email as the string representation. To change the string representation, I have overridden the default __str__() method on the User model to return str(self.id).

Here is how it can be done -

def __str__(self):
    """Return string representation of user"""
    return 'User Object ({})'.format(self.id)

Upvotes: 1

Related Questions