Search code examples
djangodjango-rest-frameworkdjango-serializer

Serialize a Post table which has a Like table connected to it by Fk


hi,since I am just noobie in DRF I need your help in serializing the Post table.
I have a Post model like this :

class Post(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    title = models.CharField(max_length=255)
    descripotion = models.TextField(blank=True)
    link = models.CharField(max_length=255, blank=True)

    def __str__(self):
        return self.title

And then there is a like Model which is related to Post model by FK

class Like(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )

    post= models.ForeignKey(
        'Post',
        on_delete=models.CASCADE
    )
    def __str__(self):
        return self.id

and this is my serializers.py for Post table

class PostSerializers(serializers.ModelSerializer):
    user = UserSerializer( required = False )

    class Meta:
        model = Post
        fields = [
            'id', 'title', 'link','user','descripotion']
        read_only_fields = ['id']

this returns the following response

{
  "id": 5,
  "title": "string",
  "link": "string",
  "user": {
    "email": "admin@mail.com",
    "name": "sia"
  },

  "descripotion": "string"
}

But I want a response to have the Like counts in it

{
  "id": 5,
  "title": "string",
  "link": "string",
  "user": {
    "email": "admin@mail.com",
    "name": "sia"
  },

  "descripotion": "string",
  "like_count": 50 
}

How shoud I change the serializer to achieve this goal?


Solution

  • You can define a new callable field with a method as serializer field:

    class PostSerializers(serializers.ModelSerializer):
        user = UserSerializer(required=False)
        like_count = serializers.SerializerMethodField('get_likes_count')
    
        def get_likes_count(self, obj: Post) -> int:
            """
            This function is called by the SerializerMethodField.
            """
            return obj.like_set.all().count()
    
        class Meta:
            model = Post
            fields = ['id', 'title', 'link','user','descripotion', 'like_count']
            read_only_fields = ['id']