From 5b5a95a41330299e22d1b1381707eb9e5482b081 Mon Sep 17 00:00:00 2001 From: "S.Mohammad Emami Razavi" Date: Wed, 21 Sep 2016 13:30:48 +0330 Subject: [PATCH] It lasts several days to find out the problem # Why we should process a prefetched model(an instance) I have nested to serializers named `Request` and `Invoice`. Also i have a primary key field named `staff` in Invoice model `staff = models.ForeignKey(User)`. Every attempts to set staff via API were failed. I were forced to see rest framework code and i found out that integer(in requested data) passed as an staff id converted to the User object(a ready and correct instance represents staff with the id). I think it is a good idea if we check it and if it's an instance and prefetched model avoid to `return self.get_queryset().get(pk=data)` it again! So i prepended an if clause to `to_internal_value` and the problem was resolved! ## related problems *. http://stackoverflow.com/questions/20681468/how-to-make-foreignkey-play-nice-with-none-in-drf *. http://stackoverflow.com/questions/25874507/django-rest-framework-serializer-expecting-pk-getting-string *. http://stackoverflow.com/questions/20681468/how-to-make-foreignkey-play-nice-with-none-in-drf ## my error message ``` {'staff': ['Incorrect type. Expected pk value, received User.']} ``` --- rest_framework/relations.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 572b69170..e92095a48 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -7,7 +7,7 @@ from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.core.urlresolvers import ( NoReverseMatch, Resolver404, get_script_prefix, resolve ) -from django.db.models import Manager +from django.db.models import Manager, Model from django.db.models.query import QuerySet from django.utils import six from django.utils.encoding import smart_text @@ -216,6 +216,8 @@ class PrimaryKeyRelatedField(RelatedField): return True def to_internal_value(self, data): + if isinstance(data, Model): + return data if self.pk_field is not None: data = self.pk_field.to_internal_value(data) try: