Getting django.db.utils.OperationalError: sub-select returns 11 columns - expected 1 when trying to add an object to a m2m field
Getting django.db.utils.OperationalError: sub-select returns 11 columns - expected 1 when trying to add an object to a m2m field
我是 django rest 框架的新手,我正在尝试构建 api 待办事项应用程序,使用它我可以将合作者添加到待办事项 我的待办事项模型如下:
class Todo(models.Model):
creator = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
collaborators = models.ManyToManyField(User,related_name='collaborators')
def __str__(self):
return self.title
Serializer.py
class TodoCreateSerializer(serializers.ModelSerializer):
def save(self, **kwargs):
data = self.validated_data
user = self.context['request'].user
title = data['title']
todo = Todo.objects.create(creator=user, title=title)
return todo
class Meta:
model = Todo
fields = ('id', 'title',)
class UserObjectSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username']
class TodoSerializer(serializers.ModelSerializer):
collaborators = UserObjectSerializer(many=True, required = False)
class Meta:
model = Todo
fields = ['id', 'title', 'collaborators']
class CollaboratorSerializer(serializers.ModelSerializer):
collaborators = UserObjectSerializer(many=True)
class Meta:
model = Todo
fields = ['collaborators']
当我尝试在视图集中使用以下方法将协作者对象添加到我的协作者字段时
class CollaboratorViewSet(viewsets.ModelViewSet):
serializer_class = CollaboratorSerializer
queryset=Todo.objects.all()
@action(methods=['put'], detail=True, permission_classes=[permissions.IsAuthenticated, ], url_path='add-collaborator', url_name='add_collaborator')
def add_collaborator(self, request, pk=None):
try:
todo = Todo.objects.get(pk=pk)
except Exception:
return Response({'Error':'Invalid Id'})
else:
if request.user == todo.creator:
try:
collborators = request.data["collaborators"]
except KeyError:
return Response({'Error':'Collaborator field not specified in request'}, status = status.HTTP_400_BAD_REQUEST)
else:
collab_list = []
for collab in collborators:
try:
collab_name = collab['username']
except KeyError:
return Response({'Error':'No username provided'}, status = status.HTTP_400_BAD_REQUEST)
else:
new_collab = User.objects.filter(username=collab_name)
if new_collab:
collab_list.append(new_collab)
else:
return Response({'detail':'No user with provided username exists'}, status = status.HTTP_400_BAD_REQUEST)
todo.collaborators.add(*collab_list)
return Response({'Success':'Added collaborators successfully'}, status=status.HTTP_200_OK)
else:
raise PermissionDenied("You are not the creator of this Todo.")
@action(methods=['patch'], detail=True, permission_classes=[permissions.IsAuthenticated, ], url_path='delete-collaborator', url_name='delete_collaborator')
我收到一个错误
django.db.utils.OperationalError: sub-select returns 11 列 - 预期 1
但是当我使用 todo.collaborators.set(collaborator_object)
添加了协作者,但是通过这种方式我只能添加一个协作者,并且当我尝试添加多个协作者时没有任何效果。
我知道我们可以使用 .add() 方法将多个对象添加到 m2m 关系字段,但是当我尝试添加一个对象时这不起作用,我还浏览了 .add() 方法的文档但找不到任何帮助。
抱歉问了这么长的问题,感谢您的提前帮助!
我设法解决了这个错误,实际上我是想以
的身份访问合作者
new_collab = User.objects.filter(username=collab_name)
这将 return 查询集,即使存在具有给定用户名的唯一用户
然后我试图将协作者直接添加到协作者字段,这导致了这个错误,因为它期望一个用户实例,但我提供了一个查询集
为了避免我只是将上面的行替换为
new_collab = User.objects.get(username=collab_name)
这将 return 一个 User 对象实例(如果它存在)所以不会引发错误并且我能够添加多个以及单个协作者。
我是 django rest 框架的新手,我正在尝试构建 api 待办事项应用程序,使用它我可以将合作者添加到待办事项 我的待办事项模型如下:
class Todo(models.Model):
creator = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
collaborators = models.ManyToManyField(User,related_name='collaborators')
def __str__(self):
return self.title
Serializer.py
class TodoCreateSerializer(serializers.ModelSerializer):
def save(self, **kwargs):
data = self.validated_data
user = self.context['request'].user
title = data['title']
todo = Todo.objects.create(creator=user, title=title)
return todo
class Meta:
model = Todo
fields = ('id', 'title',)
class UserObjectSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username']
class TodoSerializer(serializers.ModelSerializer):
collaborators = UserObjectSerializer(many=True, required = False)
class Meta:
model = Todo
fields = ['id', 'title', 'collaborators']
class CollaboratorSerializer(serializers.ModelSerializer):
collaborators = UserObjectSerializer(many=True)
class Meta:
model = Todo
fields = ['collaborators']
当我尝试在视图集中使用以下方法将协作者对象添加到我的协作者字段时
class CollaboratorViewSet(viewsets.ModelViewSet):
serializer_class = CollaboratorSerializer
queryset=Todo.objects.all()
@action(methods=['put'], detail=True, permission_classes=[permissions.IsAuthenticated, ], url_path='add-collaborator', url_name='add_collaborator')
def add_collaborator(self, request, pk=None):
try:
todo = Todo.objects.get(pk=pk)
except Exception:
return Response({'Error':'Invalid Id'})
else:
if request.user == todo.creator:
try:
collborators = request.data["collaborators"]
except KeyError:
return Response({'Error':'Collaborator field not specified in request'}, status = status.HTTP_400_BAD_REQUEST)
else:
collab_list = []
for collab in collborators:
try:
collab_name = collab['username']
except KeyError:
return Response({'Error':'No username provided'}, status = status.HTTP_400_BAD_REQUEST)
else:
new_collab = User.objects.filter(username=collab_name)
if new_collab:
collab_list.append(new_collab)
else:
return Response({'detail':'No user with provided username exists'}, status = status.HTTP_400_BAD_REQUEST)
todo.collaborators.add(*collab_list)
return Response({'Success':'Added collaborators successfully'}, status=status.HTTP_200_OK)
else:
raise PermissionDenied("You are not the creator of this Todo.")
@action(methods=['patch'], detail=True, permission_classes=[permissions.IsAuthenticated, ], url_path='delete-collaborator', url_name='delete_collaborator')
我收到一个错误 django.db.utils.OperationalError: sub-select returns 11 列 - 预期 1 但是当我使用 todo.collaborators.set(collaborator_object) 添加了协作者,但是通过这种方式我只能添加一个协作者,并且当我尝试添加多个协作者时没有任何效果。 我知道我们可以使用 .add() 方法将多个对象添加到 m2m 关系字段,但是当我尝试添加一个对象时这不起作用,我还浏览了 .add() 方法的文档但找不到任何帮助。
抱歉问了这么长的问题,感谢您的提前帮助!
我设法解决了这个错误,实际上我是想以
的身份访问合作者new_collab = User.objects.filter(username=collab_name)
这将 return 查询集,即使存在具有给定用户名的唯一用户 然后我试图将协作者直接添加到协作者字段,这导致了这个错误,因为它期望一个用户实例,但我提供了一个查询集 为了避免我只是将上面的行替换为
new_collab = User.objects.get(username=collab_name)
这将 return 一个 User 对象实例(如果它存在)所以不会引发错误并且我能够添加多个以及单个协作者。