序列化器上的Django Rest Framework条件字段 [英] Django Rest Framework Conditional Field on Serializer

查看:158
本文介绍了序列化器上的Django Rest Framework条件字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个引用通用关系我想详细序列化。

I have a model that references a Generic Relation that I want to serialize in a detailed manner.

class AType(models.Model):
    foo = CharField()


class BType(models.Model):
    bar = PositiveIntegerField()


class ToSerialize(models.Model):
    scope_limit = models.Q(app_label="app", model="atype") | \
                  models.Q(app_label="app", model="btype")
    content_type = models.ForeignKey(ContentType, limit_choices_to=scope_limit)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

我想要ToSerialize视图集的list方法的JSON如下所示:

I'd like the JSON for the list method of the ToSerialize viewset to look like:

[
    {
       "atype": { "id": 1, "foo": "a" }
    },
    {
       "atype": { "id": 2, "foo": "b" }
    },
    {
       "btype": { "id": 1, "bar": "1" }
    },
    {
       "btype": { "id": 2, "bar": "2" }
    }
]

有没有办法让ToSerialize对象的视图集的序列化程序根据将实现此效果的content_type / object_id生成条件字段?

Is there a way I can have the serializer for the ToSerialize object's viewset produce "conditional fields" based on the content_type/object_id that will achieve this effect?

推荐答案

使用 SerializeMethodField

class YourSerializer(serializers.ModelSerializer):
    your_conditional_field = serializers.SerializerMethodField()

    class Meta:
        model = ToSerialize

    def get_your_conditional_field(self, obj):
        # do your conditional logic here
        # and return appropriate result
        return obj.content_type > obj.object_id

这篇关于序列化器上的Django Rest Framework条件字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆