Home > Back-end >  When and where is `Field.blank` checked by DRF?
When and where is `Field.blank` checked by DRF?

Time:01-19

I have a model

class SomeModel(models.Model):
    emails = ArrayField(models.EmailField(), default=list)

And let's say I have the following Serializer of the model:

class SomeModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = SomeModel
        fields = ['emails']

The email field is not blank-able, i.e: It's required to set a value for it when submitting a Form of the model, or when making changes to its Admin page.

My understanding is that DRF relies as well on Django's internal machinery to validate whether emails is missing on the Serializer data or not. But the thing is that I can't find where (and when) this happens.

I've found that DRF is not calling the Model's clean() method anymore (link). But what baffles me is that changing the blank value on the field seems to have a direct impact on the Serializer. I have switched to blank=True, and then the Serializer would allow it to be saved without that field... Then I switched back to blank=False, and the Serializer would fail if emails is not present.

So do you have any idea of when and where DRF checks for a field's blank value?

Thanks!

CodePudding user response:

As far as I know, it simply doesn't. Those are only used across forms and the django admin interface.

I always specify those things on the serializer level, by setting the appropiate arguments for my fields (doc), in this case it would be allow_blank.

I am building REST APIs with django, and the only case where the blank property on the model field catches me, is when fiddling around on the admin page.

However, there appears to be a package that could be of interest to you: django-seriously.

I haven't used it, but it appears to call full_clean() on every save(). Of course, this has the disadvantage that you will probably loose DRFs nice error messages.

  • Related