Description
Checklist
- I have verified that that issue exists against the
master
branch of Django REST framework. (tested against 3.9.0 from pip) - I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
- This is not a usage question. (Those should be directed to the discussion group instead.)
- This cannot be dealt with as a third party library. (We prefer new functionality to be in the form of third party libraries where possible.)
- I have reduced the issue to the simplest possible case.
- I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.) ( Not sure how the tests are structured in DRF, but I have included a failing test in code)
Steps to reproduce
Note that this is a potential duplicate/regression of #2017
DRF's serializers do not seem to respect null/blank in relation to the reverse side of the OneToOneField. I'm unsure whether this is with this field in particular, or a more general thing.
Take the following models
# models.py
class Location(models.Model):
pass
class Company(models.Model):
main_location = models.OneToOneField(to=Location, null=True, blank=True, on_delete=models.SET_NULL, related_name="owning_company")
And the following serializer for Locations
# Serializers.py
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = ("id", "owning_company")
I would expect that DRF correctly realizes that the inverse part of the relationship is not required. I would expect the following test to pass
class TestLocationEndpoint(APITestCase):
def test_location_can_be_created(self):
# Should be able to instantiate the object without any data at all.
serializer = LocationSerializer(data = {})
serializer.is_valid(raise_exception=True)
However it fails with the following validationError:
rest_framework.exceptions.ValidationError: {'owning_company': [ErrorDetail(string='Dette felt er påkrævet.', code='required')]}
(Don't mind the translation)
If I manually set required=false
on the owning_company
field, there is no problem:
This serializer works fine
class LocationSerializer(serializers.ModelSerializer):
owning_company = serializers.PrimaryKeyRelatedField(required=False, queryset=Company.objects.all())
class Meta:
model = Location
fields = ("id", "owning_company")
Expected behavior
I expect DRF to pick up on the fact that the field is set to blank in the model, and therefore required should not be set to true as default.
Actual behavior
Required is set to true, no matter what the value of blank and null is in the model.