Reputation: 33655
I want to set a non-persistent property on a model. I have tried the following:
class class User(models.Model):
email = models.EmailField(max_length=254, unique=True, db_index=True)
@property
def client_id(self):
return self.client_id
Then:
user = User.objects.create(email='123', client_id=123)
print(user.client_id)
I get the error: can't set attribute. Why?
Upvotes: 6
Views: 2791
Reputation: 6317
You need to define a setter function for your property too, right now, it is read-only (see, e.g., this question).
class class User(models.Model):
email = models.EmailField(max_length=254, unique=True, db_index=True)
@property
def client_id(self):
return self.internal_client_id
@client_id.setter
def client_id(self, value):
self.internal_client_id = value
Note that I renamed self.client_id
to self.internal_client_id
, because otherwise, you would be calling the getter and setter functions recursively - the name of the internal variable needs to be different from the property's name.
Of course, if you need to use self.client_id
(e.g. because of inheritance), you can also rename the property itself.
Upvotes: 5