I am new to django rest and currently working on serializers to handle nested creation of objects ModelB is the object whose instance is to be created and it has a reverse relation with modelC and has a direct relation with modelA
ModelA has to fetched and passed to ModelB during its creation ModelC list is to be created alongwith ModelB
Models
class ModelA(TimeStampMixin, CoordinateMixin):
name = models.CharField(max_length=150)
class ModelB(TimeStampMixin):
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
modelA = models.ForeignKey(
ModelA,
on_delete=models.PROTECT,
related_name='modela_reverse'
)
class ModelC(TimeStampMixin):
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
modelB = models.ForeignKey(ModelB, on_delete=models.CASCADE, related_name='modelb_reverse')
modelD = models.ForeignKey(ModelD, on_delete=models.CASCADE, related_name='modelD_reverse')
class ModelD(TimeStampMixin):
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
name = models.CharField(max_length=50)
Serializers:
class ModelDSerializer(serializers.ModelSerializer):
class Meta:
model = ModelD
fields = ['name', 'uuid']
class ModelCSerializer(serializers.ModelSerializer):
modeld = ModelDSerializer(many=False)
class Meta:
model = ModelC
fields = ['modeld', 'quantity']
class ModelA(serializers.ModelSerializer):
class Meta:
model = ModelA
fields = ['name', 'uuid']
read_only_fields = ['name']
def to_internal_value(self, data):
modelA = ModelA.objects.get(**data)
return modelA
class ModelB(serializers.ModelSerializer):
modelb_reverse = ModelCSerializer(many=True)
modelA = ModelASerializer(many=False)
class Meta:
model = ModelB
fields = ['modelb_reverse', 'modelA']
Uptil now i have been able to carry the creation of ModelB through its serializer when only nested modelA is included but i am stuck at somehow modifying the solution to include the creation of reverse objects through the nested ModelCSerializer
I am finding an elegant way to achieve this and have been stuck here for a while Would really appreciate some help Thanks in advance