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?
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.
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