File tree Expand file tree Collapse file tree 2 files changed +41
-1
lines changed Expand file tree Collapse file tree 2 files changed +41
-1
lines changed Original file line number Diff line number Diff line change 35
35
)
36
36
import copy
37
37
import inspect
38
+ import sys
38
39
import warnings
39
40
40
41
# Note: We do the following so that users of the framework can use this style:
@@ -653,7 +654,18 @@ def create(self, validated_attrs):
653
654
if relation_info .to_many and (field_name in validated_attrs ):
654
655
many_to_many [field_name ] = validated_attrs .pop (field_name )
655
656
656
- instance = ModelClass .objects .create (** validated_attrs )
657
+ try :
658
+ instance = ModelClass .objects .create (** validated_attrs )
659
+ except TypeError as exc :
660
+ msg = (
661
+ 'The mentioned argument might be a field on the serializer '
662
+ 'that is not part of the model. You need to override the '
663
+ 'create() method in your ModelSerializer subclass to support '
664
+ 'this.' )
665
+ six .reraise (
666
+ type (exc ),
667
+ type (exc )(str (exc ) + '. ' + msg ),
668
+ sys .exc_info ()[2 ])
657
669
658
670
# Save many-to-many relationships after the instance is created.
659
671
if many_to_many :
Original file line number Diff line number Diff line change 10
10
from django .db import models
11
11
from django .test import TestCase
12
12
from rest_framework import serializers
13
+ import pytest
13
14
14
15
15
16
def dedent (blocktext ):
@@ -26,6 +27,10 @@ class CustomField(models.Field):
26
27
pass
27
28
28
29
30
+ class OneFieldModel (models .Model ):
31
+ char_field = models .CharField (max_length = 100 )
32
+
33
+
29
34
class RegularFieldsModel (models .Model ):
30
35
"""
31
36
A model class for testing regular flat fields.
@@ -68,6 +73,29 @@ class FieldOptionsModel(models.Model):
68
73
choices_field = models .CharField (max_length = 100 , choices = COLOR_CHOICES )
69
74
70
75
76
+ class TestModelSerializer (TestCase ):
77
+ def test_create_method (self ):
78
+ class TestSerializer (serializers .ModelSerializer ):
79
+ non_model_field = serializers .CharField ()
80
+
81
+ class Meta :
82
+ model = OneFieldModel
83
+ fields = ('char_field' , 'non_model_field' )
84
+
85
+ serializer = TestSerializer (data = {
86
+ 'char_field' : 'foo' ,
87
+ 'non_model_field' : 'bar' ,
88
+ })
89
+ serializer .is_valid ()
90
+ with pytest .raises (TypeError ):
91
+ serializer .save ()
92
+
93
+ try :
94
+ serializer .save ()
95
+ except TypeError as exc :
96
+ assert 'ModelSerializer' in str (exc )
97
+
98
+
71
99
class TestRegularFieldMappings (TestCase ):
72
100
def test_regular_fields (self ):
73
101
"""
You can’t perform that action at this time.
0 commit comments