Propagate 'default' from model_field to serializer field. by rnshaikh · Pull Request #9030 · encode/django-rest-framework (original) (raw)
Hi!
After upgrading from DRF 3.14 to 3.15 our tests broke when a model serializer that allows required=False for a non-nullable field in the corresponding model is now ignored so the endpoint that uses the serializer to create the object throws an error claiming you need to provide the value for the field.
However, the value that eventually goes into the field of the model might be managed in the create method of the serializer and set there.
In this example there is an entity_id field that refers to an entity field on the model. The entity_id does not need to be provided by the user as other information are used to create the Entity objects and assign to the entity field of the Customer model in the create method of the serializer.
class CustomerDetailSerializer(serializers.ModelSerializer):
entity_id = EntityForeignKey(source="entity", write_only=True, allow_null=True, required=False)
class Customer(models.Model):
entity = models.ForeignKey("users.Entity", related_name="customers", on_delete=models.PROTECT)