django 用户未保存在多对多字段drf中

pcrecxhr  于 2023-03-04  发布在  Go
关注(0)|答案(1)|浏览(131)

我正在学习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“”对象不可迭代”}

nqwrtyyt

nqwrtyyt1#

首先,将users字段修改为具有子CharFieldListField,以便可以将用户名列表作为输入传递。
此外,使用to_representation()方法返回用户名列表,而不是ManyRelatedManager对象,因此:

class BlogSerializer(serializers.ModelSerializer):
    users = serializers.ListField(child=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

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['users'] = list(instance.users.all().values_list('username', flat=True))
        return ret

相关问题