I am building an app using django and drf. While testing a serializer, I found the serializer could not save data to database because of null constraints. Below is the test code, serializer and model.
location_serializer_data: LocationDict = {
'address': 'address',
'latitude': 11.1,
'longitude': 22.2,
}
@pytest.mark.django_db
def test_deserializing(self):
serializer = LocationSerializer(data=location_serializer_data)
serializer.is_valid()
new_location = serializer.save() # < where the test explodes
Here is the error message
django.db.utils.IntegrityError: NOT NULL constraint failed: locations_location.latitude
I found that serializer.initial_data
gets the data appropriately, but after serializer.is_valid()
, two of serializer.data
, serializer.validated_data
become blank dict.
I searched a bit but I found no clue of what was causing this.
CodePudding user response:
I think the following code should help you
@pytest.mark.django_db
def test_deserializing(self):
serializer = LocationSerializer(data=location_serializer_data)
serializer.is_valid(raise_exception=True) # < Now code will raise error here
new_location = serializer.save()
This will ensure that exception is raised at the validation level
CodePudding user response:
.is_valid() method validates but does not raise the error by itself. We can do serializer.is_valid(raise_exception=True). It raises validation error if the data is not valid.
CodePudding user response:
One possible cause is that the the field latitude
does not exists in the LocationSerializer
because it got "cleaned out" by the serializer validation. If it's possible, please share the detail on LocationSerializer
so we can help further.