I have been looking at extending the Django user model, and while I am confident I can make it work, there is a line of code that I really want to understand.
I have been referencing the following tutorial: http://blog.tivix.com/2012/01/06/extending-user-model-in-django/
but I can not for the life of me understand how the following line of code works:
User.profile = property(lambda u: u.get_profile() )
If I understand correctly, this sets the getter method for User.profile to an anonymous function that takes a user as an argument and returns the profile, BUT, if I am referencing myuser.profile, when is the argument actually passed?
I hope I communicated myself properly. Any help understanding this would be greatly appreciated!
It'd probably make more sense they wrote it this way
User.profile = property(lambda self: self.get_profile())
Or more verbosely:
class UserProfile(models.Model):
user = models.OneToOneField(User)
@property
def profile(self):
return self.get_profile()
def __str__(self):
return "%s's profile" % self.user
The first argument of every instance method of a Python object is the instance of the class to which the method belongs. self
is just a convention, so u
works just as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With