简体   繁体   English

Django Rest Framework-如何序列化模型类名称库

[英]Django rest framework - how to serialise the model class name base serialiser?

I have a BaseModel class: 我有一个BaseModel类:

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

Then I have mutliple model classes that extend such class eg: 然后我有多个扩展此类的模型类,例如:

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

My goal is to have a field in a JSON object returned through my webservices to indicate the type of the object (so that the client applications can easily tell an Article from a e-commerce Product). 我的目标是在通过我的Web服务返回的JSON对象中具有一个字段,以指示对象的类型(以便客户端应用程序可以轻松地从电子商务产品中告知商品)。 Something like the following: 类似于以下内容:

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

I imagine the there could be a BaseModelSerializer class similar to the following: 我想可能会有一个类似于以下内容的BaseModelSerializer类:

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

Then I can have a ArticleSerializer extending the BaseModelSerializer like the following: 然后,我可以使用ArticleSerializer扩展BaseModelSerializer ,如下所示:

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

I would be happy if this could be achieved through modifying the BaseModel class too. 如果可以通过修改BaseModel类来实现这一点,我将感到高兴。 Something like the following? 类似于以下内容?

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

Use SerializerMethodField . 使用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',)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM