I'm using Django 2.x
I have a model like
class MyModel(models.Model):
name = models.CharField()
balance = models.IntegerField()
I want to change the value of balance on the GET request without changing the value in the database.
Like if it could be @Property field, the model will look like
class MyModel(models.Model):
name = models.CharField()
balance = models.IntegerField()
@property
def balance(self):
if balance:
return balance
return 0.15 * 50
But redeclaration is not allowed. How can I solve this issue?
Note: Field should be compatible with ModelAdmin and DRF Serializer
There are two ways. Either by using a getter/setter and hide the actual table field. That would allow you to use myobject.balance
like any regular field in the model, assigning to it with myobject.balance = 123
and reading from it print(myobject.balance)
etc.
class MyModel(models.Model):
name = models.CharField()
_balance = models.IntegerField()
@property
def balance(self):
if self._balance:
return self._balance
return 0.15 * 50
@balance.setter
def balance(self, value):
self._balance = value
Using a leading _
is the Python convention for "hidden" (private) fields.
A second and simpler way would be to simply use a get_balance()
function, and not use a property.
def get_balance(self):
if self.balance:
return self.balance
return 0.15 * 50
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