gpt4 book ai didi

django - 禁用在 django rest 框架中创建嵌套对象

转载 作者:行者123 更新时间:2023-12-04 20:41:52 24 4
gpt4 key购买 nike

你好,

你能帮我怎么做禁止创建嵌套对象 ?

我有这样的序列化程序:
(员工拥有团队的外键)

class TeamSerializer(serializers.ModelSerializer):
class Meta:
model = Team
fields = ('id', 'name')
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('id', 'name', 'surname', 'team')
depth = 1

或者可以是:
class EmployeeSerializer(serializers.ModelSerializer):
team = TeamSerializer()
class Meta:
model = Employee
fields = ('id', 'name', 'surname', 'team')

当我发布 json 时(创建员工)
{
name: "name",
surname: "surname",
team: {
id: 1,
name: "Web Team"
}
}

对象员工创建,但对象团队...
有什么方法可以禁用与员工一起创建团队对象吗?
我只想创建员工并将选定的团队(当前在数据库中)设置为员工

在 GET (list) 上,我希望能够检索
数据如:
{
name: "name",
surname: "surname",
team: {
id: 1,
name: "Web Team"
}

不是这样的
{
name: "name",
surname: "surname",
team: 1
}

有没有办法在 django rest 框架中做到这一点(我也使用 angular)

问候

更新

目前的序列化程序:
class TeamSerializer(serializers.ModelSerializer):
class Meta:
model = Team

class EmployeeSerializer(serializers.ModelSerializer):
team = TeamSerializer()

class Meta:
model = Employee

我不能使用 serializers.RelatedField() 因为它只返回 unicode 我需要“id”和“name”(我想)

这是我的 POST json: ( Restangular.all('employee').post(data) )
data: {
name: "emp1",
photo: "",
skype: "",
surname: "qweqwe",
team: {
id: 1,
name: "Web",
}
}

和 DRF 返回 json:
employee: {
id: 2,
name: "emp1",
photo: "",
skype: "",
surname: "qweqwe",
team: {
id:3, <-- NEW ID!
name: "Web"
}
}

所以是的,我确信创建了新的团队对象。所以现在怎么办 ?:)

最佳答案

我发现 ModelSerializer.to_native()ModelSerializer.from_native()在最新版本的 DRF 中不存在。我从公认的解决方案中提出了以下内容:

class PlayerSerializer(serializers.ModelSerializer):
class Meta:
model = Player
fields = ('id', 'name', 'team')

def to_internal_value(self, data):
# If team is not a dict, such as when submitting via the Browseable UI, this would fail.
try:
data['team'] = data['team']['id']
except TypeError:
pass
return super(PlayerSerializer, self).to_internal_value(data)

def to_representation(self, instance):
return ReadPlayerSerializer(instance).data


class ReadPlayerSerializer(serializers.ModelSerializer):
team = TeamSerializer()

class Meta(PlayerSerializer.Meta):
pass

实际上,似乎 from_native现在是 to_representation , 和 to_native是不是 to_internal_value

关于django - 禁用在 django rest 框架中创建嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25088473/

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