I am using a DRF view function (with an @api_view(["POST"])
decorator) to use user posted data to create a new database record for a model Product
. I have in my model definition Meta
unique_together = ["user", "name"]
. I would like to ensure that this unique together constraint is checked in a serializer validation itself, so as to avoid raising an integrity error at the time of saving.
So what I used to try earlier was request.data["user"] = request.user.id
, before passing request.data
to the model serializer, then calling serializer.is_valid()
, and finally serializer.save()
. However, this used to raise some error to the effect that request.data
was not modifiable when I was using some DRF 3.12.x (and Django 3.2). This was a minor inconvenience as I had to create a copy of request.data
to modify the posted data. This kind of thing is described in multiple places, for e.g., here on SO and elsewhere.
But I have since upgraded to DRF 3.13.1 and I noticed that now I am able to modify request.data
in ways that I was not able to earlier (adding a new key-value pair, popping or editing the value for an existing key). I am testing using Postman: the type of request.data
showed as QueryDict
when I posted using form data, and dict
when I posted json. In either case, I am able to modify it.
Is this allowed in DRF now? And, is this safe to do or is something wrong with my code?