我有一个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)


我的目标是在通过我的Web服务返回的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

最佳答案

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

10-05 18:17