iamafasha
iamafasha

Reputation: 794

Is there a way to add custom fields in Django Rest Framework

I am creating a rest API for my Django blog project and I have models Post and PostLike models as you below:

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    text = models.TextField()
    approved = models.BooleanField(default=False)
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField( default=timezone.now, blank=True, null=True)
    def publish(self):
        self.published_date = timezone.now()
        self.save()
    def __str__(self):
        return self.text[0:100]

class PostLike(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE)
    created_date = models.DateTimeField(default=timezone.now)

And I have a Post serialiser like

class PostSerializers(ModelSerializer):
    likes_count = serializers.IntegerField(read_only=True)
    class Meta:
        model= Post
        fields = ['id','text','author', 'approved','created_date', 'likes_count' ]

I wish the likes_count to be count for the PostLike objects with the post of the queried post. What is the right way to implement it?

Upvotes: 0

Views: 48

Answers (1)

Demetris
Demetris

Reputation: 3241

The SerializerMethodField allows you to return a value based on the return value of a class method.

EDIT: Note that the method accepts the object as a parameter. Therefore to achieve what you want, you can return:

def like_count(self, obj):
    return obj.postlike_set.count()

Upvotes: 1

Related Questions