1

Using Django Rest Framwork, I want to set a field that can not be null in the Database, but that's not included in the fields tuple on the Meta class, before i actually save the model that the ModelSerializer manages.

In my ViewSet, I define perform_create and want to do something like this:

serializer.fields.new_field = new_field_id

where new_field is a Foreign Key on my model and new_field.id is the id of the model i just fetched using a value set on the cookie.

Does anyone know a clean solution to this?

Thanks!

2
  • Checkout this question Commented Mar 1, 2015 at 5:53
  • @Todor Another solution. Three already! Thanks Commented Mar 1, 2015 at 11:49

1 Answer 1

5

Do you mean this..?

def perform_create(self, serializer):
    serializer.save(user=self.request.user)
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm i tried that as well, it then tells me: user is an invalid keyword argument for this function. I settled for a middleware solution where i modify request.POST on each request.method == "POST". This works pretty good since i need to add the field to multiple resources and can depend on DRF's built in validators. It helps with DRY though i read it's not a great idea to modify request.POST
Ok shucks, PyCharm had me there. It suggested a different kwarg, i just realised the name of my model field was different from the one PyCharm suggested.. I appears i now have two valid solutions. Great & Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.