我正在尝试将request.user添加到manytomany字段中以创建项目。但我收到此错误:
/ api / v1 / movies /中的TypeError “用户”对象不可迭代
Models.py Movie(models.Model)类:
class Movie(models.Model):
title = models.CharField(max_length=100)
genre = models.CharField(max_length=100)
year = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
owners = models.ManyToManyField('auth.User', related_name='movies')
views.py
# Create a new movie
def post(self, request):
serializer = MovieSerializer(data=request.data)
if serializer.is_valid():
serializer.save(owners=request.user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
答案 0 :(得分:0)
每个评论和更新的问题,所需的行为 是多个用户。假设您的MovieSerializer
是ModelSerializer
的子类,并且您为PrimaryKeyRelatedField
序列化程序字段使用了默认(owners
)绑定,则您应该能够在初始数据中添加requestor
:
def post(self, request):
serializer = MovieSerializer(data=dict(request.data, owners=[request.user.id]))
if serializer.is_valid():
serializer.save()
...
注意::由于owners
是一种ManyToMany
关系,因此您需要将用户保留在数组中,并且要进行序列化,必须将其设置为pk
用户,而不是对象。