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

Viewed 590

I'm working with Django Framework. I have two models: Component and 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)

And serializers:

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')

I'm trying to load data with fixtures. I wrote and fixture file that look like this:

[
   {
      "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
         ]
      }
   }
]

That's work fine! But I have 20 fixtures to load. I want to have fixture (component.json for example) look like this bellow:

[
   {
      "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",

               }
            }
         ]
      }
   }
]

The icing on the cake must be fixtures specifying a primary key like here. Please, can anyone help me to write these fixtures without pk and the relationships described above?

1 Answers
Related