简体   繁体   中英

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

I have a BaseModel class:

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). 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:

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:

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

I would be happy if this could be achieved through modifying the BaseModel class too. 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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