Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelSerializer using model property

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?

like image 229
Sander Smits Avatar asked Jun 12 '13 12:06

Sander Smits


People also ask

How do I pass Queryset to serializer?

To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.

How do you serialize an object in Django REST framework?

Creating and Using Serializers To create a basic serializer one needs to import serializers class from rest_framework and define fields for a serializer just like creating a form or model in Django.

Why do we use Serializers in Django REST framework?

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON , XML or other content types.

What is model serializer in Django?

The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields. The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model.


2 Answers

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')
like image 154
Tom Christie Avatar answered Sep 19 '22 08:09

Tom Christie


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__"
like image 35
suhailvs Avatar answered Sep 19 '22 08:09

suhailvs