Let's say we have three Models : ModelA, related to ModelB and ModelC.
ModelA is defined as :
class ModelA(models.Model):
field_b = models.ForeignKey(ModelB, on_delete=models.CASCADE)
field_c = models.ForeignKey(ModelC, on_delete=models.CASCADE)
other_field = models.CharField(max_length=30)
class Meta:
constraints = [
models.UniqueConstraint(fields=['field_b', 'field_c'], name='unique_modelA')
]
- How to generate a ModelASerializer instance from instances of ModelB and ModelC ?
- Then, will there be a serialized representation of field_b and field_c into ModelASerializer ?
- The UniqueConstraint will it be checked when calling .is_valid() onto ModelASerializer instance ?
I tried the following :
class ModelASerializer(serializers.ModelSerializer):
field_b = ModelBSerializer(read_only=True)
field_c = ModelCSerializer(read_only=True)
other_field = serializers.CharField(required=False)
class Meta:
model = ModelA
fields = ('field_b', 'field_c', 'other_field',)
validators = [
UniqueTogetherValidator(
queryset=ModelA.objects.all(),
fields=['field_b', 'field_c'],
message='A Model A instance for this couple of ModelB and ModelC instances already exists.'
)
]
def create(self, validated_data):
"""
Create and return a new `ModelA` instance, given the validated data.
"""
return ModelA.objects.create(**validated_data)
def update(self, instance, validated_data):
"""
Update and return an existing `ModelA` instance, given the validated data.
"""
instance.other_field= validated_data.get('other_field', instance.other_field)
instance.save()
return instance
But I cannot find any way to create the serializer :
model_b = ModelB()
model_c = ModelC()
model_b.save()
model_c.save()
other_field = "Dummy content"
First try
model_a_serializer = ModelASerializer(model_b, model_c, other_field)
- The serializer is looking for an ID field and can't find it
- Anyway, no data field being provided, we can't call .is_valid() onto the serializer, and thus, can't check the integrity constraint
Second try
model_b_serializer = ModelBSerializer(model_b)
model_c_serializer = ModelCSerializer(model_c)
data = {'model_b':model_b_serializer , 'model_c':model_c_serializer , 'other_field':other_field}
model_a_serializer = ModelASerializer(data=data)
if model_a_serializer.is_valid():
model_a_serializer.save()
Here, the serializer tries to recreate the ModelB and ModelC instances when is_valid() is called... And I don't want that.
Any ideas? Thank you very much by advance.