Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python can't set attribute on non-persistent property

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?

like image 652
Prometheus Avatar asked Dec 09 '15 13:12

Prometheus


1 Answers

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.

like image 94
hlt Avatar answered Sep 26 '22 02:09

hlt