Issue
I have some models in my project and I need a especial response of the API, i'm using Django Rest framework.
class Goal(models.Model):
name = models.CharField()
# more fields
class Task(models.Model):
name = models.CharField()
goal = models.ForeignKey(Goal)
class UserTask(models.Model):
goal = models.ForeignKey(Goal)
user = models.ForeignKey(User)
# other fields
I have this response:
{
"name": "One goal",
"task": [
{
"name": "first task"
},
{
"name": "second tas"
}
]
}
But I need this:
{
"name": "One goal",
"task": [
{
"name": "first task",
"is_in_usertask": true
},
{
"name": "second tas",
"is_in_usertask": false
}
]
}
I saw this in DRF docs but I don't know how to filter UserTask
by the current user (or other that is given in URL paramenter) and each Goal
.
Edit:
# serializers
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
class GoalSerializer(serializers.ModelSerializer):
# related_name works fine
tasks = TaskSerializer(many=True)
class Meta:
model = Goal
Solution
try to use SerializerMethodField
field as
class TaskSerializer(serializers.ModelSerializer):
is_in_usertask = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Task
fields = ('name', 'is_in_usertask')
def get_is_in_usertask(self, task):
return UserTask.objects.filter(user=self.context['request'].user, goal=task.goal).exists()
Answered By - JPG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.