3

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

2 Answers2

5

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()
JPG
  • 82,442
  • 19
  • 127
  • 206
  • I tried this, but I don't knew how to access to the user instance. I will try this. To access to url parameters is the same way? – Christian Torres Jul 25 '18 at 14:26
  • Serializer's ,`context` contains few data by default, that are `request` and `view`. Django has the feature to get the logged-in user via `request.user` attribute – JPG Jul 25 '18 at 17:23
  • URL params are the attributes od request object. Which means that are accessible from your serializer as long as the context has request instance – JPG Jul 25 '18 at 17:25
0

Take a look to this conversation: How to get Request.User in Django-Rest-Framework serializer?

You can't access to request.user directly

Pavel Minenkov
  • 368
  • 2
  • 9