Home > Net >  Property field not appearing in django serializer
Property field not appearing in django serializer

Time:05-19

I have a property inside a Django model, I have to show it inside the serializer. I put the field inside the serializer, but it's not coming up in the response.

class Example(models.Model):    

    field_1 = models.ForeignKey(
        Modelabc, on_delete=models.CASCADE, null=True, related_name="abc"
    )

    field_2 = models.ForeignKey(
        Modelxyz,
        on_delete=models.CASCADE,
        null=True,
        related_name="xyz",
    )    

    name = models.CharField(max_length=25, blank=True)

    
    @property
    def fullname(self):
        if self.name is not None:
             return "%s%s%s" % (self.field_1.name, self.field_2.name, self.name)
        return "%s%s" % (self.field_1.name, self.field_2.name)

Serializer is like this:

class ExampleSerializer(serializers.ModelSerializer):

    
    fullname = serializers.ReadonlyField()

    class Meta:
        model = Example
        fields = [
            "id",
            "fullname",]

When I call the get API for this, the fullname is not being displayed in the api response. What is the issue?

CodePudding user response:

@property attributes are not included in Django Serializer fields as only Django model fields are shown. I normally use the following workaround for this.

  1. Create a SerializerMethodField.
  2. Return object.property from the method.

So, your Serializer class would be:

class ExampleSerializer(serializers.ModelSerializer):
    fullname = serializers.SerializerMethodField()

    class Meta:
        model = OnlineClass
        fields = [
            "id",
            "fullname",
        ]
    
    def get_fullname(self, object):
        return object.fullname

CodePudding user response:

I think, in ExampleSerializer class, the model should be Example not OnlineClass and the fields should contain all the fields inside the model.

  • Related