Xzibit jokes aside, here's my model:
from django.db import models
class ProjectProfitAndLoss(models.Model):
pass
class Component(models.Model):
profit_and_loss = models.ForeignKey(ProjectProfitAndLoss, related_name='components')
name = models.CharField(max_length=250)
class ComponentProductionVolume(models.Model):
component = models.ForeignKey(Component, related_name='volumes')
offset = models.IntegerField()
volume = models.DecimalField(max_digits=16, decimal_places=4)
Serializers:
from rest_framework import serializers
class ComponentProductionVolumeSerializer(serializers.ModelSerializer):
class Meta:
model = ComponentProductionVolume
class ComponentSerializer(serializers.ModelSerializer):
volumes = ComponentProductionVolumeSerializer(many=True, allow_add_remove=True)
class Meta:
model = Component
class ProjectProfitAndLossSerializer(serializers.ModelSerializer):
components = ComponentSerializer(many=True, allow_add_remove=True)
class Meta:
model = ProjectProfitAndLoss
What I'm trying to do is post Components to be created as a list along with their ComponentProductionVolumes - also as lists. So my json looks something like this:
[
{
"name": "component 1",
"profit_and_loss": 3,
"volumes": [
{
"offset": 0,
"volume": 2
},
{
"offset": 1,
"volume": 3
},
{
"offset": 2,
"volume": 2
},
]
},
{
"name": "component 2"
"profit_and_loss": 3,
"volumes": [
{
"offset": 0,
"volume": 4
},
{
"offset": 1,
"volume": 2
},
{
"offset": 2,
"volume": 5
},
]
}
]
Unfortunately, what I'm getting back is a validation error:
components: [{volumes:[{component:[This field is required.]},{volumes:[{component:[This field is required.]} ... /* error repeated for each volume sent */ ]}]
If I understand correctly, this errors tell me to include component id in each volume I send. But since I want DRF to create Components along with their volumes, this is not possible, because Components don't exist yet.
What would be the best approach to make DRF create components, and then ComponentProductionVolumes?