I have model and serializer with JSONField
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
detail = models.JSONField(default=dict)
def __str__(self):
return self.user.username
class ProfileSerializer(ModelSerializer):
class Meta:
model = m.Profile
fields = '__all__'
Then,I want to set the data to serializer class,
However some how serializer.is_valid()
faild.
I have tested two pettern data1
data2
temp_data = {"data":"test"}
data1 = {"detail":temp_data} # test_data1
data2 = {"detail":json.dumps(temp_data)} # test_data2
print(data1) # {'detail': {'data': 'test'}}
print(data2) # {'detail': '{"data": "test"}'}
instance = self.get_object()
serializer = self.get_serializer(instance,data = data1) # or data2
if serializer.is_valid():
# serializer
else:
print("is_valid failed")
What data should I give to this serializer?
And is there any method to debug is_valid()?
CodePudding user response:
You are giving the data in right way, but as you are updating partially, you need to pass one more parameter:
serializer = self.get_serializer(instance, data=data1, partial=True)
To debug the is_valid
method, you can either throw exceptions from it like .is_valid(raise_exception=True)
; or in your code, print serializer.errors
in else block to print the exact errors. More information on validation can be found in documentation.