ModelSerializer using model property

2019-02-02 02:04发布

I'm trying to serialize a model containing a property field that I also want to serialize.

models.py:

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    slug = models.AutoSlugField(populate_from='name')

    @property
    def ext_link(self):
        return "/".join([settings.EXT_BASE_URL, self.slug])

serializers.py:

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('name', 'ext_link')

When trying to get to the related URL, I'm getting a serializer exception (KeyError) on the ext_link property.

How can I serialize the ext_link property?

2条回答
Emotional °昔
2楼-- · 2019-02-02 02:18

as @Robert Townley's comment, this work with version 3.8.2:

class MyModelSerializer(serializers.ModelSerializer):
    ext_link = serializers.ReadOnlyField()

    class Meta:
        model = MyModel
        fields = "__all__"
查看更多
够拽才男人
3楼-- · 2019-02-02 02:23

Because it's not a model field, it needs to be added explicitly to the serializer class

class MyModelSerializer(serializers.ModelSerializer):
    ext_link = serializers.Field()

    class Meta:
        model = MyModel
        fields = ('name', 'ext_link')

Edit: In REST framework 3 adding to fields will just work - don't need to add the field explicitly.

查看更多
登录 后发表回答