I have a simple Model
that stores the user that created it with a ForeignKey
. The model has a corresponding ModelSerializer
and ModelViewSet
.
The problem is that when the user submits a POST
to create a new record, the user
should be set by the backend. I tried overriding perform_create
on the ModelViewSet
to set the user, but it actually still fails during the validation step (which makes sense). It comes back saying the user
field is required.
I'm thinking about overriding the user
field on the ModelSerializer
to be optional, but I feel like there's probably a cleaner and more efficient way to do this. Any ideas?
You can make the
user
field asread_only.
This will ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.
In your serializers, you can do something like:
You can then override the
perform_create()
and set theuser
as per your requirements.I came across this answer while looking for a way to update values before the control goes to the validator.
This might be useful for someone else - here's how I finally did it (DRF 3) without rewriting the whole validator.
For those who're curious, I used this to round decimal values to precision defined in the model so that the validator doesn't throw errors.