0

我在这里有个问题

我有两个模型

标签模型

class Tag(models.Model):
    creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='author')
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

轮廓模型

class Profile(models.Model):
    profiler = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='contour')
    bio = models.TextField(blank=True, null=True)
    tags = models.ManyToManyField(Tag, blank=True, related_name='keywords')
    image = models.ImageField(default='avatar.jpg', upload_to='images', blank=True, null=True)

    def __str__(self):
        return f'{self.profiler}'

标签序列化器

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = '__all__'

配置文件序列化器

class ProfileSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, read_only=True)

    class Meta:
        model = Profile
        fields = ['id',  # List All fields Exclude profiler => OneToOne field name
                  'bio', 'description',
                  'tags',
                  'image',
                  'birthDate', 'created', 'updated',
                  ]
        depth = 1

轮廓视图集

class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = [IsAuthenticated]

def partial_update(self, request, *args, **kwargs):
    data = request.data

    profile_obj = Profile.objects.update(
        profiler=self.request.user,
        bio=data['bio'],
        image=data['image'],
    )

    profile_obj.save()

    for tag in data['tags']:
        tag_obj = Tag.objects.update_or_create(
            creator=self.request.user,
            name=tag['name'],  # name => Field Name in Tag Model
        )

        print(tag_obj)
        profile_obj.tags.add(tag_obj)  # tags => ManyToMany Field Name in Profile Model

    serializer = ProfileSerializer(profile_obj)

    return Response(serializer.data)

如果此名称不存在,我的目标是创建一个新标签,并更新个人资料标签

但我的代码不起作用,我不知道为什么

任何机构都可以帮忙吗?

4

1 回答 1

0

最后我找到了解决方案,但它仍然缺少一些步骤

配置文件序列化器

class ProfileSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True)  # tags = ManyToMany Field Name

    class Meta:
        model = Profile

        fields = ['id',  # List All fields Exclude profiler => OneToOne field name
                  'bio', 'description',
                  'tags',
                  'image', 'get_image',
                  'birthDate', 'created', 'updated',
                  ]

    def update(self, instance, validated_data):
        # Clear Existing Tags List Before Creating a New One By user
        instance.tags.clear()

        tags_data = validated_data.pop('tags')
        instance = super(ProfileSerializer, self).update(instance, validated_data)

        for tag_data in tags_data:
            tag_qs = Tag.objects.filter(name__iexact=tag_data['name'])

            if tag_qs.exists():
                tag = tag_qs.first()
            else:
                tag = Tag.objects.create(**tag_data, creator=self.instance.profiler)

            instance.tags.add(tag)

        return instance

它就像一个魅力,但问题是:当我想部分更新字段并且我没有提交标签字段时,它会引发错误

{
    "tags": [
        "This field is required."
    ]
}

当更新的数据缺少标签字段时,有人可以帮助保持我的标签列表吗

提前致谢

于 2022-02-11T08:27:05.007 回答