I want a nice convenient attribute to do the following:
from django.contrib.auth.models import User
user = User.objects.get(id=2)
user.company
<Company: Big Company L.L.C>
I am currently solving this using lambda. In searching for an answer it looks like perhaps the “right” way to solve this would be to use types.MethodType but I can’t seem to get my head around it. Yes, I have read Raymond excellent guide but I’m clearly missing something.. Here is my current solution for those who are interested..
# Defined Elsewhere
class User:
name = models.CharField(max_length=32)
class Company(models.Model):
users = models.ManyToManyField(User, related_name="companies", blank=True, null=True)
# Here is the meat of this..
class UserProfile(models.Model):
"""This defines Users"""
user = models.OneToOneField(User)
def get_company(self):
try:
companies = self.user.companies.all()[0]
except (AttributeError, IndexError):
return None
User.company = property(lambda u: UserProfile.objects.get_or_create(user=u)[0].get_company())
Right now this works.. But is there a better way – I’m not crazy about lambdas??
I’m not quite sure I understand correctly what your goal is, but from what I think I understand, it doesn’t seem necessary to do any crazy stuff with descriptors here, let alone
types.MethodType. A simple property is fine, and if you don’t like the lambda, you can use an ordinary function decorated with@property:Edit: If you can’t touch the
Userclass, you can create a derived class adding the desired property: