如何从django中具有@property装饰器的模型类序列化函数

时间:2018-03-23 06:50:06

标签: django python-3.x django-models django-rest-framework django-views

我正在使用django_rest框架,我想知道如何序列化具有@property装饰器的函数。在这种情况下,从下面的代码我有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

我知道在serializers.py我将从做这样的事情开始:

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

2 个答案:

答案 0 :(得分:1)

解决方案是,定义SerializerMethodField()如下,

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',)

答案 1 :(得分:1)

您可以使用IntegerField()并将read_only设置为true,

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

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