我在这里有个问题
我有两种型号的
标签型号
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)
我的目标是创建一个新的标签,如果这个名称不存在,还更新配置文件标签
但我的代码不起作用,我不知道为什么
有人能帮忙吗?
最后我找到了解决方案,但它仍然缺少一些步骤
配置文件序列化程序
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."
]
}
当更新的数据丢失标签字段时,有人能帮助保持我的标签列表吗
提前感谢