我正在使用Django和REST框架。我正在定义一个APIView,在其中,我使用create()创建一个ORM对象。我传递给create函数的一个字段是失败的,说它不是一个有效的关键字参数。这是我正在添加的新领域。该字段存在于模型和序列化程序中。另一个类似的新领域并没有失败。
回溯:
Internal Server Error: /api/new_thing
Traceback (most recent call last):
File "/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/local/lib/python2.7/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/local/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/local/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/other_app/rest_apis.py", line 336, in post
flag=false
File "/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/local/lib/python2.7/site-packages/django/db/models/query.py", line 346, in create
obj = self.model(**kwargs)
File "/local/lib/python2.7/site-packages/django/db/models/base.py", line 480, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'doohickeys' is an invalid keyword argument for this function
API查看:
class NewThing(APIView):
renderer_classes = (JSONRenderer,)
serializer_class = StuffSerializer
@detail_route(methods=['POST'])
def post(self, request, pk, format=None):
# do stuff
whatsits_list = [] # list of ORM objects
doohickeys_list = [] # list of ORM objects
thing = Thing.objects.create(
whatsits=whatsits_list, # this is not failing
doohickeys=doohickeys_list, # this is failing
flag=false
)
# return some stuff
型号:
from django.db import models
from other_app.models import Doohickey, Whatsit
class Thing(models.Model):
whatsits = models.ManyToManyField('other_app.Whatsit', related_name='things', blank=True)
doohickeys = models.ManyToManyField('other_app.Doohickey', related_name='things', blank=True)
flag = models.BooleanField(default=True)
串行:
class StuffSerializer(serializers.ModelSerializer):
doohickeys = serializers.PrimaryKeyRelatedField(queryset=Doohickey.objects.all(), many=True, allow_empty=True)
class Meta:
model = Stuff
fields = ('id',
'doohickeys',
'whatsits',
'public',
)
知道为什么我在doohickey键上出错了吗?我已经尝试使用调试器来跟踪代码,看起来它是REST框架APIView类中的dispatch()函数捕获的异常。
谢谢!
答案 0 :(得分:2)
在保存对象之前,您不能使用多对多字段,因为它实际上是一个使用每边对象ID的直通表。因此,首先创建对象,然后添加doohickeys。
thing = Thing.objects.create(...)
thing.doohickeys.add(*doohickeys_list)
请注意,你所做的事情很奇怪。 django-rest-framework的重点在于你使用了序列化器,它为你处理了所有这些逻辑 - 你已经定义了一个序列化器,但是你没有使用它,你似乎完全绕过了它。 / p>