gpt4 book ai didi

django - 如何通过显式添加对象的字段在 Django fixtures 中添加关系?

转载 作者:行者123 更新时间:2023-12-02 01:09:31 25 4
gpt4 key购买 nike

我正在使用 Django 框架。我有两个模型:Component 和 ComponentProperty。

class Component(models.Model):
name = models.CharField(unique=True, max_length=255)
component_properties = models.ManyToManyField(ComponentProperty)

class ComponentProperty(models.Model):
label = models.CharField(unique=True, max_length=255)
component_type = models.CharField(max_length=255)

和序列化器:

class ComponentSerializer(serializers.ModelSerializer):
class Meta:
model = Component
fields = ('name', 'component_properties')
depth = 1

class ComponentPropertySerializer(serializers.ModelSerializer):
class Meta:
model = ComponentProperty
fields = ('label', 'component_type')

我正在尝试使用固定装置加载数据。我编写了如下所示的夹具文件:

[
{
"pk":1,
"model":"api.componentproperty",
"fields":{
"label":"label",
"component_type":"text"
}
},
{
"pk":2,
"model":"api.componentproperty",
"fields":{
"label":"description",
"component_type":"text",

}
},
{
"pk":1,
"model":"api.component",
"fields":{
"name":"text",
"component_properties":[
1,
2
]
}
}
]

这很好!但我有 20 个固定装置要加载。我想要固定装置(例如 component.json)如下所示:

[
{
"pk":null,
"model":"api.component",
"fields":{
"name":"text",
"component_properties":[
{
"pk":null,
"model":"api.componentproperty",
"fields":{
"label":"label",
"component_type":"text"
}
},
{
"pk":null,
"model":"api.componentproperty",
"fields":{
"label":"description",
"component_type":"text",

}
}
]
}
}
]

锦上添花的必须是指定主键的固定装置,如 here .拜托,任何人都可以帮我写这些没有 pk 和上述关系的装置吗?

最佳答案

据我了解,您想在 ComponentSerializer 中对 Component properties 执行嵌套序列化

如果在 ComponentSerializer 中使用 ComponentPropertySerializer 就可以做到:

class ComponentPropertySerializer(serializers.ModelSerializer):
class Meta:
model = ComponentProperty
fields = ('label', 'component_type')


class ComponentSerializer(serializers.ModelSerializer):
# Django REST Framework supports nested serialization
# You serialize your *component_properties* with your ComponentPropertySerializer
# As they are many properties, you use *many=True*

component_properties = ComponentPropertySerializer(many=True, read_only=True)

class Meta:
model = Component
fields = ('name', 'component_properties')
depth = 1

我认为这应该会重现所需的输出。嵌套序列化非常有用,在 Django REST Framework's docs 中有详细记录。 .

关于django - 如何通过显式添加对象的字段在 Django fixtures 中添加关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45711716/

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