Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
D
django-rest-framework
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
edx
django-rest-framework
Commits
853c7a16
Commit
853c7a16
authored
Apr 13, 2014
by
Ian Foote
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Use setattr for adding fields to a new instance
Add test for restoring a GenericForeignKey
parent
0a0e4f22
Show whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
22 additions
and
6 deletions
+22
-6
rest_framework/serializers.py
+4
-6
rest_framework/tests/test_genericrelations.py
+18
-0
No files found.
rest_framework/serializers.py
View file @
853c7a16
...
...
@@ -955,18 +955,16 @@ class ModelSerializer(Serializer):
if
isinstance
(
self
.
fields
.
get
(
field_name
,
None
),
Serializer
):
nested_forward_relations
[
field_name
]
=
attrs
[
field_name
]
# Update an existing instance...
if
instance
is
not
None
:
# Create an empty instance of the model
if
instance
is
None
:
instance
=
self
.
opts
.
model
()
for
key
,
val
in
attrs
.
items
():
try
:
setattr
(
instance
,
key
,
val
)
except
ValueError
:
self
.
_errors
[
key
]
=
self
.
error_messages
[
'required'
]
# ...or create a new instance
else
:
instance
=
self
.
opts
.
model
(
**
attrs
)
# Any relations that cannot be set until we've
# saved the model get hidden away on these
# private attributes, so we can deal with them
...
...
rest_framework/tests/test_genericrelations.py
View file @
853c7a16
...
...
@@ -131,3 +131,21 @@ class TestGenericRelations(TestCase):
}
]
self
.
assertEqual
(
serializer
.
data
,
expected
)
def
test_restore_object_generic_fk
(
self
):
"""
Ensure an object with a generic foreign key can be restored.
"""
class
TagSerializer
(
serializers
.
ModelSerializer
):
class
Meta
:
model
=
Tag
exclude
=
(
'content_type'
,
'object_id'
)
serializer
=
TagSerializer
()
bookmark
=
Bookmark
(
url
=
'http://example.com'
)
attrs
=
{
'tagged_item'
:
bookmark
,
'tag'
:
'example'
}
tag
=
serializer
.
restore_object
(
attrs
)
self
.
assertEqual
(
tag
.
tagged_item
,
bookmark
)
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment