Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django getter on model field

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

like image 327
Anuj TBE Avatar asked Mar 16 '19 13:03

Anuj TBE


1 Answers

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
like image 101
C14L Avatar answered Sep 20 '22 01:09

C14L