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 34
34
)
35
35
import copy
36
36
import inspect
37
+ import sys
37
38
import warnings
38
39
39
40
# Note: We do the following so that users of the framework can use this style:
@@ -593,7 +594,18 @@ def create(self, validated_attrs):
593
594
if relation_info .to_many and (field_name in validated_attrs ):
594
595
many_to_many [field_name ] = validated_attrs .pop (field_name )
595
596
596
- instance = ModelClass .objects .create (** validated_attrs )
597
+ try :
598
+ instance = ModelClass .objects .create (** validated_attrs )
599
+ except TypeError as exc :
600
+ msg = (
601
+ 'The mentioned argument might be a field on the serializer '
602
+ 'that is not part of the model. You need to override the '
603
+ 'create() method in your ModelSerializer subclass to support '
604
+ 'this.' )
605
+ six .reraise (
606
+ type (exc ),
607
+ type (exc )(str (exc ) + '. ' + msg ),
608
+ sys .exc_info ()[2 ])
597
609
598
610
# Save many-to-many relationships after the instance is created.
599
611
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