Using Django Rest Framework, I am attempting to add a model object via POST, specifying the id of an existing object to which the new object should have a foreign key. Works. If I add a depth=1 to the new object's serializer however, so that I get the foreign key target in a GET, the POST to add a new object fails with a mysql error 'IntegrityError: (1048, "Column 'reportdefinition_id' cannot be null")', even though I specify a valid foreign key id in my POST.
I can work around this by leaving the depth = 1 out and retrieving the reportdefinition separately in my client, but that's cumbersome.
(I found two related questions, but neither answers mine: Django REST - Create object with foreign key using serializers Need to show Foreign Key Object in Details by Django Rest Framework)
Models (I've not shown irrelevant fields):
class ReportDefinition(models.Model):
name = models.CharField(max_length=254, blank=True, null=True)
class ReportRun(models.Model):
status = models.IntegerField(default=2)
reportdefinition = models.ForeignKey(ReportDefinition)
Serializers:
class ReportDefinitionSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = models.ReportDefinition
fields = ("id","name")
class ReportRunSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
depth = 1
model = models.ReportRun
fields =("id","status","reportdefinition")
If I remove 'depth = 1', the POST works.
class ReportRunSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
class Meta:
model = models.ReportRun
fields =("id","status","reportdefinition")
The POST contents (again, irrelevant other attributes not shown):
reportdefinition:1
One thing I noticed: without the depth = 1, the DRF browsable API shows "reportdefinition" in its default, but with depth = 1, it does not. I have to add it explicitly.
DRF browsable API content with depth = 1:
{
"status": null,
}
(I add "reportdefinition": 1 when issuing the POST, and verify that it appears using Chrome Developer Tools)
DRF browsable API content with no 'depth = 1':
{
"status": null,
"reportdefinition": null
}
(I replace null with 1 when issuing the POST)