user3134477 user3134477 - 5 days ago 6
reST (reStructuredText) Question

Making a custom Boolean field in Django REST Framework

I'm new to django rest framework.

The relevant part of my models looks something like this (simplified):

class Action(models.Model):
type = models.CharField()
bonus = models.IntegerField()

class User(models.Model):
auth = models.OneToOneField(AuthUser)
display_name = models.CharField()

class Comment(models.Model):
contributor = models.ForeignKey(User)
content = models.TextField()

class Activity(models.Model):
user = models.ForeignKey(User)
target_comment = models.ForeignKey(Comment)
action = models.ForeignKey(Action)


I want one of my API endpoints to be able to return something like this:

{
...
"comments":
[
{
"id": 1,
...
"curr_user_upvoted": true
},
...
]
}


I know the query I need to execute in order to get the value for "curr_user_upvoted", but I don't know how to make it part of the API representation.

I know how to create custom relational fields, but it doesn't help since "curr_user_upvoted" is neither a field nor a relation.

Any idea?

Answer

You can create a SerializerMethodField to do this. This is just a method on the serializer class that returns the value you want.

The method name defaults to get_curr_user_upvoted - in other words it should be get_ followed by the field name, though you can pass an explicit method_name parameter to the field if you prefer.

Comments