我正在学习django rest框架,我的Blog
模型中有一个名为users
的字段,ManyToManyFieldtoUser,我正在尝试在.post()
请求中保存多个用户。
models.py
class Blog(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
users = models.ManyToManyField(User, related_name="users")
views.py
class BlogCreateView(mixins.CreateModelMixin,
GenericAPIView):
serializer_class = BlogSerializer
queryset = Blog.objects.all()
def post(self, request, pk, *args, **kwargs):
try:
return self.create(request, *args, **kwargs)
except Exception as e:
return Response({"error": "something went wrong"},)
serializers.py
class BlogSerializer(serializers.ModelSerializer):
users = serializers.CharField()
class Meta:
model = Blog
fields = "__all__"
def create(self, validated_data):
user_usernames = validated_data.pop('users', [])
blog = Blog.objects.create(**validated_data)
users = User.objects.filter(username__in=user_usernames)
blog.users.set(users)
return blog
当我传递用户名字符串如“user 1”,“user 2”时,它不保存。
然后我想传递用户名字符串可能是反模式,然后我尝试将CharField转换为ListField,如下所示
users = serializers.ListField(child=serializers.CharField())
但后来发现
{“错误”:“”ManyRelatedManager“”对象不可迭代”}
1条答案
按热度按时间nqwrtyyt1#
首先,将
users
字段修改为具有子CharField
的ListField
,以便可以将用户名列表作为输入传递。此外,使用
to_representation()
方法返回用户名列表,而不是ManyRelatedManager
对象,因此: