Django休息框架 - 如何序列化模型类名称base serialiser?

时间:2015-10-02 07:06:24

标签: python json django inheritance django-rest-framework

我有一个 BaseModel 类:

class BaseModel(models.Model):
    title = models.CharField(max_length=250, blank=True, null=True)
    class Meta:
        abstract = True

然后我有多个扩展这样的类的多个模型类,例如:

class Article(BaseModel):
    slug = models.SlugField(max_length=250, default=timezone.now, unique=True)

我的目标是通过我的webservices返回一个JSON对象中的字段来指示对象的类型(以便客户端应用程序可以轻松地从电子商务产品中分辨文章)。如下所示:

{
   "id": 1,
   "object_type: "article",
   "title": "some article",
   "slug": "some-article"
}

我想可能有一个类似于以下的 BaseModelSerializer 类:

class BaseModelSerializer(serializers.ModelSerializer):
    object_type = self.__class__.__name__ # ??? how to get the name/ label of the child class?

然后我可以使用 ArticleSerializer 扩展 BaseModelSerializer ,如下所示:

class ArticleSerializer(BaseModelSerializer):
    class Meta:
        model = Article

如果可以通过修改 BaseModel 类来实现这一点,我会很高兴。像下面这样的东西?

class BaseModel(models.Model):
    title = models.CharField(max_length=250, blank=True, null=True)
    object_type = self.__class__.__name__ # ??? how to get the name/ label of the child class?
    class Meta:
        abstract = True

1 个答案:

答案 0 :(得分:1)

使用SerializerMethodField

class BaseModelSerializer(serializers.ModelSerializer):
    object_type = serializers.SerializerMethodField()

    def get_object_type(obj):
        return obj.__class__.__name__.lower()


class ArticleSerializer(BaseModelSerializer):
    class Meta:
        model = Article
        fields = ('object_type',)