我在这里有个问题
我有两个模型
标签模型
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)
如果此名称不存在,我的目标是创建一个新标签,并更新个人资料标签
但我的代码不起作用,我不知道为什么
任何机构都可以帮忙吗?