Python cannot set attribute for mutable property

I want to set a mutable property in a model. I 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 an error: cannot set attribute . Why?

+4
source share
1 answer

You also need to define the setter function for your property, now it is read-only (see, for example, 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

Please note that I renamed self.client_idto self.internal_client_id, because otherwise you would call the getter and setter functions recursively - the name of the internal variable must be different from the name of the property.

, self.client_id (, - ), .

+4

Source: https://habr.com/ru/post/1619207/


All Articles