在ManyToMany字段中添加request.user

时间:2019-05-09 18:54:47

标签: django django-rest-framework

我正在尝试将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)

1 个答案:

答案 0 :(得分:0)

每个评论和更新的问题,所需的行为 是多个用户。假设您的MovieSerializerModelSerializer 的子类,并且您为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用户,而不是对象。