NotImplementedError: RelatedField.to_representation() must be implemented for field /// How to serialize a method/ForeignKey/@property

Another day another Django Rest Framework error.

It is a short solution yet the one that took some time to get to.

If you you need values of your ForeignKey, method or property, make it a @property and use this tried and true solution.

For models.py:

class Reply(models.Model):
   quote = models.ForeignKeyField('self', on_delete=models.CASCADE)

I want the following serializer to work:

class Reply_serial(serializers.ModelSerializer):
   
   class Meta:
      model = Reply
      fields = [
            'id',
            'quote_id'
            ]

Just like that you in case you don’t have quote value, in response there will be:

"quote_id": null

But it is not exactly very friendly. It would be preferable to have 0 instead of null. For that you may want to make a method, but it won’t work very well. So, make a property. In models.py:

class Reply(models.Model):
   quote = models.ForeignKeyField('self', on_delete=models.CASCADE)
   
   @property
   def get_pk(self):
        return self.quote.pk if self.quote else 0

And in your serializer:

class Reply_serial(serializers.ModelSerializer):
   quote_id = serializers.ReadOnlyField(source='get_pk')
   class Meta:
      model = Reply
      fields = [
            'id',
            'quote_id'
            ]

And voila!

"quote_id": 0

References

2 thoughts on “NotImplementedError: RelatedField.to_representation() must be implemented for field /// How to serialize a method/ForeignKey/@property

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.