mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-07 13:54:47 +03:00
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.']} ```
This commit is contained in:
parent
1823662e1e
commit
5b5a95a413
|
@ -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:
|
||||
|
|
Loading…
Reference in New Issue
Block a user