DRF,将自定义字段添加到ModelSerializer

时间:2018-07-25 07:43:35

标签: python django django-rest-framework

我的项目中有一些模型,我需要API的特殊响应,我正在使用Django Rest框架。

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

我有这个回应:

{
  "name": "One goal",
  "task": [
    {
      "name": "first task"
    },
    {
      "name": "second tas"
    }
  ]
}

但是我需要这个:

{
  "name": "One goal",
  "task": [
    {
      "name": "first task",
      "is_in_usertask": true
    },
    {
      "name": "second tas",
      "is_in_usertask": false
    }
  ]
}

我看到了this in DRF docs,但是我不知道如何通过当前用户(或URL参数中的其他用户)和每个UserTask来过滤Goal

编辑:

# 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 个答案:

答案 0 :(得分:0)

看看这个对话:How to get Request.User in Django-Rest-Framework serializer?

您无法直接访问request.user

答案 1 :(得分:0)

尝试将SerializerMethodField字段用作

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()