当我在Postman中发布嵌套的序列化程序时,会出现以下错误
"profile": {
"non_field_errors": [
"Invalid data. Expected a dictionary, but got list."
]
}
但是当我发出GET请求时,它会像这样显示
"email": null,
"phone_number": null,
"profile": {
"first_name": "Jane",
"last_name": "Doe",
"interestlist_set": [
{
"interest_list": [
2,
1
],
"user": 1,
"category": 1
}
]
我要在上面发布与上面相同的内容,interest_list是ManyToManyField
,可能是问题,但我无法解决,这是我的模型
models.py
class InterestName(TimeModel):
name = models.CharField(max_length=255)
class InterestList(models.Model):
interest_list = models.ManyToManyField(InterestName)
user = models.ForeignKey(Profile, on_delete=models.CASCADE)
category = models.ForeignKey(ListOfInterestCategory, on_delete=models.CASCADE)
class Profile(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
first_name = models.CharField(max_length=30, null=True)
last_name = models.CharField(max_length=30, null=True)
serializers.py
class ProfileSerializer(serializers.ModelSerializer):
interestlist_set = InterestListSerializer(many=True)
class Meta:
model = Profile
fields = ['first_name', 'last_name', 'interestlist_set',]
class UserRegisterSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()
class Meta:
model = CustomUser
fields = ['email', 'phone_number','profile']
def create(self, validated_data):
profiles_data = validated_data.pop('profile')
user = CustomUser.objects.create(**validated_data)
for profile_data in profiles_data:
Profile.objects.create(user=user, **profile_data)
return user
到目前为止,我在这里一直尝试无法在Postman中发出POST请求的方法如何解决此问题?预先感谢!