I have model and serializer with JSONField
JavaScript
x
12
12
1
class Profile(models.Model):
2
user = models.OneToOneField(User,on_delete=models.CASCADE)
3
detail = models.JSONField(default=dict)
4
5
def __str__(self):
6
return self.user.username
7
8
class ProfileSerializer(ModelSerializer):
9
class Meta:
10
model = m.Profile
11
fields = '__all__'
12
Then,I want to set the data to serializer class,
However some how serializer.is_valid()
faild.
I have tested two pettern data1
data2
JavaScript
1
17
17
1
temp_data = {"data":"test"}
2
3
data1 = {"detail":temp_data} # test_data1
4
data2 = {"detail":json.dumps(temp_data)} # test_data2
5
6
print(data1) # {'detail': {'data': 'test'}}
7
print(data2) # {'detail': '{"data": "test"}'}
8
9
instance = self.get_object()
10
11
serializer = self.get_serializer(instance,data = data1) # or data2
12
13
if serializer.is_valid():
14
# serializer
15
else:
16
print("is_valid failed")
17
What data should I give to this serializer?
And is there any method to debug is_valid()?
Advertisement
Answer
You are giving the data in right way, but as you are updating partially, you need to pass one more parameter:
JavaScript
1
2
1
serializer = self.get_serializer(instance, data=data1, partial=True)
2
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.