Really confused about what’s going on here. I have a class defined as follows:
class Profile(models.Model):
user = models.OneToOneField(User)
primary_phone = models.CharField(max_length=20)
address = models.ForeignKey(Address)
@property
def primary_email(self): return self.user.email
@primary_email.setter
def primary_email(self, val): self.user.email = val
NB: user has an attribute email.
Now from the commandline, I’m trying this:
>>> u = User.objects.get(pk=1)
>>> u.email = 'xxx'
>>> u.profile.primary_email
u'yyy'
It spits out a different value? Specifically, the old value of u.email. What’s going on? How is this possible? I basically just want to create an alias for email.
Some more info:
>>> id(u) == id(u.profile.user)
False
>>> u
<User: mark>
>>> u.profile.user
<User: mark>
They seem to be different copies of user, but they… what? Both start with the same values?
Doing this seems to commit the changes:
>>> u.profile.primary_email = 'yyy'
>>> u.profile.user.save()
But u.save() won’t do the trick because u != u.profile.user for whatever reason. I guess that answers my question, but it’s still kind of lame.
It is possible for those two to refer to the same object in Python, right? It was just a funny design decision in Django that’s causing this?
Python properties per se do not work in django models because django’s models do some magic to set instance attributes. Maybe this is having an effect.