Reputation: 3270
I'm working on a small project and I have a user profile page.
This page has a variable called user. This variable contains the user object of the current profile page. The logged in user object is accessible with request.user
If you just print the user object it will return the username because the model returns this in the __str__
function
What is the best way to compare if the user profile belongs to the current user?
I could just write
if user == request.user
But what if django changes the return value of the __str__
function?
or I could write
if user.username == request.user.username
or
if user.id == request.user.id
Upvotes: 4
Views: 1732
Reputation: 72261
Roman Miroshnychenko answered the question already, just a small addendum:
Looks like the question originated because you assumed that ==
comparison would internally call the __str__
function. This is not the case.
The __str__
method is sometimes called implicitly, but only in well defined places, like:
print(obj)
'{0}'.format(obj)
or f'{obj}'
or '%s' % obj
There's also the __repr__
method that is called implicitly in other places, such as after each value in Python interactive shell:
>>> a = SomeObject()
>>> a
<__main__.SomeObject object at 0x7f5f218889e8>
However the ==
operator doesn't touch any of that and calls the __eq__
method instead. Hope that helps!
Upvotes: 4
Reputation: 3366
I think that if user.pk == request.user.pk
will be the best practice, because every user have different PKs(Primary Keys), so there will be no chance of any mess in your web app.
Upvotes: 0
Reputation: 1564
if user == request.user:
is the correct way. Comparison is based on database primary keys, not on string representations. Django docs: https://docs.djangoproject.com/en/2.0/topics/db/queries/#comparing-objects
Upvotes: 11