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

How to add relationships in Django fixtures by explicitly adding object's fields?

我正在使用 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.

中有详细记录