django model get field method

Viewed 1717

I have a requirement, when a field say Price in a django model Lead is accessed I have to apply some business logic and update the price.

I can accomplish in Serializers / Views. However this object is accessed by several views and hence its not a viable design to have a code in several place.

So i'm looking for a way where i can get control like get_price(self).

class Lead(models.Model):
    price = models.IntegerField(_('price'), default=10)

    def get_price(self):
    ''' Looking for something like this '''
    .. Logic ...
    return self.price

get_price to be called when any serializers/ views access this model. The issue is get_price is not getting invoked when this model is accessed.

2 Answers

you can use the property method of the class. Which will access through the objects. You can just include that fields in the serializer.

class Lead(models.Model):
    price = models.IntegerField(_('price'), default=10)

   @property
   def total_price(self):
      ''' Looking for something like this '''
      .. Logic ...
      return self.price

now you can include total_prcie field in serializer.

class LeadSerializer(serializers.ModelSerializer):
     class Meta:
          model = Lead
          fields = ('total_prize', )

I completed this task in a very different way, I had to create another table known as TrackLead Table to track when changes where made.

Later in __init__ function i updated the price field when required. I didnt find anyother way to complete it. However its working now .

Related