gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:15:41 25 4
gpt4 key购买 nike

我的项目中有一些模型,我需要 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 参数中给出的其他用户)和每个 Goal 过滤 UserTask

编辑:

# 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

最佳答案

尝试使用SerializerMethodField字段为

class TaskSerializer(serializers.ModelSerializer):
<b>is_in_usertask = serializers.SerializerMethodField(read_only=True)</b>

class Meta:
model = Task
fields = ('name', <b>'is_in_usertask'</b>)

<b>def get_is_in_usertask(self, task):
return UserTask.objects.filter(user=self.context['request'].user, goal=task.goal).exists()</b>

关于python - DRF,将自定义字段添加到 ModelSerializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51513455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com