我的模型Condition
有一个字段symptoms
,它带有多个不同的Symptoms
个对象。每当我发出POST请求来创建一个Condition对象时,我都会收到以下错误:
'条件:癫痫'需要具有字段“条件”的值才能使用这种多对多关系。
以上'条件:癫痫'嵌套在<>之间,但是发布格式有问题。
这是我的条件模型:
class Condition(models.Model):
class Treatment():
SURGERY, NON_INVASIVE, PRESCRIPTION_MEDICINE, NONE = range(4)
CHOICES = (
(SURGERY, 'Surgery'),
(NON_INVASIVE, 'Non-Invasive Treatment'),
(PRESCRIPTION_MEDICINE, 'Prescription Medicine'),
(NONE, 'None')
)
class Medicalfield(models.Model):
ONCOLOGY, CARDIOLOGY, NEPHROLOGY, PEDIATRICS, ENDOCRONOLOGY, PSYCHOLOGY = range(6)
CHOICES = (
(ONCOLOGY, 'Oncology'),
(CARDIOLOGY, 'Cardiology'),
(NEPHROLOGY, 'Nephrology'),
(PEDIATRICS, 'Pediatrics'),
(ENDOCRONOLOGY, 'Endocronology'),
(PSYCHOLOGY, 'Psychology')
)
name = models.CharField(max_length=200)
contagious = models.BooleanField()
treatable = models.BooleanField()
treatment = models.IntegerField(choices=Treatment.CHOICES, null=True)
severeity = models.IntegerField(default=0)
symptoms = models.ManyToManyField('Symptom', blank=True)
medicalfield = models.IntegerField(choices=Medicalfield.CHOICES, null=True)
new = ConditionManager()
def __unicode__(self):
return u"%s" % ( self.name )
这是我的Serializer
class ConditionSerializer(serializers.ModelSerializer):
def create(self, validated_data):
attrs = validated_data
request = self.context['request']
return Condition.new.create_condition(**attrs)
class Meta:
model = Condition
fields = ('id', 'treatment', 'name', 'contagious', 'treatable', 'treatment', 'severeity', 'symptoms', 'medicalfield')
这是经理
class ConditionManager(models.Manager):
use_in_migrations = True
use_for_related_fields=True
def create_condition(self, *args, **kwargs):
condition_obj = conditions.models.Condition(name=kwargs['name'], contagious=kwargs['contagious'], treatable=kwargs['treatable'], treatment=kwargs['treatment'], severeity=kwargs['severeity'], symptoms=kwargs['symptoms'], medicalfield=kwargs['medicalfield'])
condition_obj.save()
return condition_obj
这是视图
@api_view(['POST'])
@permission_classes((AllowAny, ))
def create_condition(request):
context = {'request': request}
symptoms = request.data['symptoms']
symptoms = Symptom.objects.filter(name__in=symptoms)
s = []
for symptom in symptoms:
s.append(symptom.pk)
request.data['symptoms'] = s
serializer = ConditionSerializer(data=request.data, context=context)
if serializer.is_valid():
serializer.save()
return response.Response(serializer.data, status=201)
return response.Response(serializer.errors, status=400)
追踪(最近一次呼叫最后一次):
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 474, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 52, in handler
return func(*args, **kwargs)
File "/Users/user/medicalrecords/conditions/views.py", line 28, in create_condition
serializer.save()
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 214, in save
self.instance = self.create(validated_data)
File "/Users/user/medicalrecords/conditions/serializers.py", line 24, in create
return Condition.new.create_condition(**attrs)
File "/Users/user/medicalrecords/conditions/managers.py", line 17, in create_condition
condition_obj = conditions.models.Condition(name=kwargs['name'], contagious=kwargs['contagious'], treatable=kwargs['treatable'], treatment=kwargs['treatment'], severeity=kwargs['severeity'], symptoms=kwargs['symptoms'], medicalfield=kwargs['medicalfield'])
File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 550, in __init__
setattr(self, prop, kwargs[prop])
File "/Library/Python/2.7/site-packages/django/db/models/fields/related_descriptors.py", line 499, in __set__
manager = self.__get__(instance)
File "/Library/Python/2.7/site-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__
return self.related_manager_cls(instance)
File "/Library/Python/2.7/site-packages/django/db/models/fields/related_descriptors.py", line 783, in __init__
(instance, self.source_field_name))
ValueError: "<Condition: epilepsy>" needs to have a value for field "condition" before this many-to-many relationship can be used.
[22/Feb/2017 20:01:45] "POST /conditions/new/condition/ HTTP/1.1" 500 15799
来自@snakefcz回答的追溯
内部服务器错误:/ conditions / new / condition / Traceback(最近一次调用最后一次): 文件“/Library/Python/2.7/site-packages/django/core/handlers/exception.py”,第39行,内部 response = get_response(request) 在_get_response中输入文件“/Library/Python/2.7/site-packages/django/core/handlers/base.py”,第187行 response = self.process_exception_by_middleware(e,request) 在_get_response中输入文件“/Library/Python/2.7/site-packages/django/core/handlers/base.py”,第185行 response = wrapped_callback(request,* callback_args,** callback_kwargs) 在wrapped_view中输入文件“/Library/Python/2.7/site-packages/django/views/decorators/csrf.py”,第58行 return view_func(* args,** kwargs) 文件“/Library/Python/2.7/site-packages/django/views/generic/base.py”,第68行,在视图中 return self.dispatch(request,* args,** kwargs) 发送文件“/Library/Python/2.7/site-packages/rest_framework/views.py”,第477行 response = self.handle_exception(exc) 在handle_exception中输入文件“/Library/Python/2.7/site-packages/rest_framework/views.py”,第437行 self.raise_uncaught_exception(EXC) 发送文件“/Library/Python/2.7/site-packages/rest_framework/views.py”,第474行 response = handler(request,* args,** kwargs) 文件“/Library/Python/2.7/site-packages/rest_framework/decorators.py”,第52行,处理程序 return func(* args,** kwargs) 在create_condition中的文件“/Users/user/medicalrecords/conditions/views.py”,第45行 return response.Response(serializer.data,status = 201) 文件“/Library/Python/2.7/site-packages/rest_framework/serializers.py”,第527行,数据 ret = super(Serializer,self).data 文件“/Library/Python/2.7/site-packages/rest_framework/serializers.py”,第262行,数据 self._data = self.to_representation(self.instance) 文件“/Library/Python/2.7/site-packages/rest_framework/serializers.py”,第496行,在to_representation中 ret [field.field_name] = field.to_representation(属性) 文件“/Library/Python/2.7/site-packages/rest_framework/serializers.py”,第643行,在to_representation中 self.child.to_representation(item)for iterable中的item 文件“/Library/Python/2.7/site-packages/rest_framework/serializers.py”,第479行,在to_representation中 fields = self._readable_fields 文件“/Library/Python/2.7/site-packages/django/utils/functional.py”,第35行,获取 res = instance。 dict [self.name] = self.func(instance) 在_readable_fields中输入文件“/Library/Python/2.7/site-packages/rest_framework/serializers.py”,第373行 self.fields.values()中字段的字段 在字段中输入文件“/Library/Python/2.7/site-packages/rest_framework/serializers.py”,第359行 for key,self.get_fields()。items()中的值: 在get_fields中输入文件“/Library/Python/2.7/site-packages/rest_framework/serializers.py”,第1010行 fields [field_name] = field_class(** field_kwargs) 在 init 中输入文件“/Library/Python/2.7/site-packages/rest_framework/fields.py”,第733行 super(CharField,self)。 init (** kwargs) TypeError: init ()得到了一个意外的关键字参数'view_name'
答案 0 :(得分:0)
除了Symptom
之外,您还需要创建Condition
序列化程序。您的ConditionSerializer
应该类似于:
class ConditionSerializer(serializers.ModelSerializer):
symptoms = SymptomSerializer(read_only=True, many=True, allow_null=True)
class Meta:
model = Condition
fields = ('id', 'treatment', 'name', 'contagious', 'treatable', 'treatment', 'severeity', 'symptoms', 'medicalfield')
def create(self, validated_data):
attrs = validated_data
request = self.context['request']
return Condition.new.create_condition(**attrs)
答案 1 :(得分:0)
## Try it
@api_view(['POST'])
@permission_classes((AllowAny, ))
def create_condition(request):
context = {'request': request}
serializer = ConditionSerializer(data=request.data, context=context)
if serializer.is_valid():
condition = serializer.save()
symptoms = request.data['symptoms']
for symp in symptoms:
symptom = Symptom.objects.get(id=symp) ## if it's id's you are passing
condition.symptoms.add(symptom)
return response.Response(serializer.data, status=201)
return response.Response(serializer.errors, status=400)