简体   繁体   中英

DRF, add custom field to ModelSerializer

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

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

You can't access to request.user directly

try to use SerializerMethodField field as

class TaskSerializer(serializers.ModelSerializer):
    

    class Meta:
        model = Task
        fields = ('name', )

    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM