Philip Mutua
Philip Mutua

Reputation: 6891

How to serialize a function from a model class that has @property decorator in django

I am using django_rest framework and I would like to know how do I serialize a function that has a @property decorator. In this case from the code below I have total_salary

class SalaryDetail(models.Model):
    employee = models.ForeignKey(Employee)
    year = models.IntegerField()
    month = models.CharField(max_length=2,
                                choices=MONTH_CHOICES)

    basic = models.PositiveSmallIntegerField()
    da = models.PositiveSmallIntegerField()
    hra = models.PositiveSmallIntegerField()
    allowance = models.PositiveSmallIntegerField(default=0)

    loss_of_pay = models.PositiveSmallIntegerField(default=0)

    repayment_of_loan = models.PositiveSmallIntegerField(default=0)

    @property
    def total_salary(self):
        return self.basic + self.da + self.hra + self.allowance

I know that in the serializers.py I will start by doing something like this:

class SalaryDetailSerializer(serializers.ModelSerializer):
     class Meta:
          model: SalaryDetail

Upvotes: 1

Views: 973

Answers (2)

A. J. Parr
A. J. Parr

Reputation: 8026

You can use an IntegerField() with read_only set to true,

class SalaryDetailSerializer(serializers.ModelSerializer):
    total_salary = serializers.IntegerField(read_only=True)

    class Meta:
        model = SalaryDetail
        fields = ('total_salary',)

Upvotes: 2

JPG
JPG

Reputation: 88619

Solution is, define a SerializerMethodField() as below,

class SalaryDetailSerializer(serializers.ModelSerializer):
    total_salary = serializers.SerializerMethodField()

    def get_total_salary(self, model):
        return model.total_salary()

    class Meta:
        model = SalaryDetail
        fields = ('total_salary',)

Upvotes: 1

Related Questions