作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
你好,
你能帮我怎么做禁止创建嵌套对象 ?
我有这样的序列化程序:
(员工拥有团队的外键)
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')
{
name: "name",
surname: "surname",
team: {
id: 1,
name: "Web Team"
}
}
{
name: "name",
surname: "surname",
team: {
id: 1,
name: "Web Team"
}
{
name: "name",
surname: "surname",
team: 1
}
class TeamSerializer(serializers.ModelSerializer):
class Meta:
model = Team
class EmployeeSerializer(serializers.ModelSerializer):
team = TeamSerializer()
class Meta:
model = Employee
data: {
name: "emp1",
photo: "",
skype: "",
surname: "qweqwe",
team: {
id: 1,
name: "Web",
}
}
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/
我是一名优秀的程序员,十分优秀!