我可以在API中添加Model函数属性吗?

时间:2018-05-14 11:00:10

标签: python django django-rest-framework

我可以在API中添加Model函数属性吗?

我有一个模特:

class PhysicalServer(models.Model):
    name = name = models.CharField(max_length=32)
    trade_record = models.ForeignKey(to=TradeRecord, null=True, blank=True)

    @property
    def is_applied(self):
        if self.trade_record == None:
            return False
        else:
            return True

我的PhysicalServerListAPIView

class PhysicalServerListAPIView(ListAPIView):
    serializer_class = PhysicalServerListSerializer
    permission_classes = [AllowAny]
    queryset = PhysicalServer.objects.all()

PhysicalServerListSerializer

class PhysicalServerListSerializer(ModelSerializer):

    class Meta:
        model = PhysicalServer
        fields = "__all__"

我有一个要求,如何将is_applied添加到列表API?

我的意思是,如果我访问ListAPI,结果数据将是:

{
  name: xxx,
  trade_record: xxx
},
...

我该如何添加?

{
  name: xxx,
  trade_record: xxx
  is_applied: xxx
},
...

2 个答案:

答案 0 :(得分:0)

只需将字段描述添加到序列化程序

即可
from rest_framework import serializers

class PhysicalServerListSerializer(ModelSerializer):
    is_applied = serializers.BooleanField(read_only=True)

    class Meta:
        model = PhysicalServer
        fields = "__all__"

答案 1 :(得分:0)

我认为SerializerMethodField正是您在寻找的。

试试这种方式。

class PhysicalServerListSerializer(ModelSerializer):
    is_applied = serializers.SerializerMethodField()

    class Meta:
        model = PhysicalServer
        fields = "__all__"

    def get_is_applied(self, obj):
        return self.trade_record is not None:

了解更多信息:http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield