ModelSerializer using model property

2019-02-02 02:17发布

问题:

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?

回答1:

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.



回答2:

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__"