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

时间:2017-08-16 10:57:59

标签: django django-models django-rest-framework django-serializer django-fixtures

我正在使用Django Framework。我有两个模型: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个装置加载。我想让fixture(例如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和上述关系的灯具吗?

1 个答案:

答案 0 :(得分:1)

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

如果您在ComponentPropertySerializer

中使用ComponentSerializer,则可以这样做
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中有详细记录。