我正在尝试使用Django REST框架找到遇到此问题的优雅解决方案.我们有一个带有子对象和一对一关系的父模型.我们的要求是子对象是可选的,可以为null,也可以从先前存在的值修补为null.此外,如果删除父对象,则子对象也应该是.
这个简单的设置可以重现问题:
class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child class ParentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Parent parent_value = serializers.CharField(required=False, max_length=1024) child = ChildSerializer(read_only=False, required=False, many=False) class Parent(models.Model): class Meta: app_label = "testparent" parent_value = models.CharField(max_length=1024, null=True, blank=True) class Child(models.Model): class Meta: app_label = "testparent" child_value = models.CharField(max_length=1024, null=True, blank=True) parent = models.ForeignKey(Parent, null=True, blank=True, related_name="child") class ParentViewSet(viewsets.ModelViewSet): permission_classes = (AllowAny,) queryset = Parent.objects.all() serializer_class = ParentSerializer
这有效:
{ "parent_value": "abc", "child": { "child_value": "something" } }
这会出错:
{ "parent_value": "abc", "child": null }
请注意,子对象是可选的,默认情况下,REST框架使用null填充该字段.
我正在使用Django v.1.5.4和REST框架v.2.3.13
错误:
Traceback: File "{site-packages}/django/core/handlers/base.py" in get_response 115. response = callback(request, *callback_args, **callback_kwargs) File "{site-packages}/rest_framework/viewsets.py" in view 78. return self.dispatch(request, *args, **kwargs) File "{site-packages}/django/views/decorators/csrf.py" in wrapped_view 77. return view_func(*args, **kwargs) File "{site-packages}/rest_framework/views.py" in dispatch 400. response = self.handle_exception(exc) File "{site-packages}/rest_framework/views.py" in dispatch 397. response = handler(request, *args, **kwargs) File "{site-packages}/rest_framework/mixins.py" in create 54. self.object = serializer.save(force_insert=True) File "{site-packages}/rest_framework/serializers.py" in save 596. self.save_object(self.object, **kwargs) File "{site-packages}/rest_framework/serializers.py" in save_object 1023. setattr(obj, accessor_name, related) File "{site-packages}/django/db/models/fields/related.py" in __set__ 474. manager.add(*value) Exception Value: add() argument after * must be a sequence, not NoneType
我们当前使用的解决方法是为父级提供OneToOne字段,然后使用post_delete信号处理程序删除子对象.这感觉非常hacky.我们一般在尝试操作嵌套对象时遇到了一些问题,并且想知道我们是否错了,或者在这种情况下我们遇到了django或其他框架中的错误.
谢谢!