django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

3.15 is raising required error on model blank fields

Open sshishov opened this issue 5 months ago • 2 comments

This issue is very similar to https://github.com/encode/django-rest-framework/issues/9378 but the problem is happening with the CharField(blank=True,...).

It is not recommended to use null=True with CharField because of double empty values like None and '', therefore we are using the blank=True to mark the field not required (kind of).

Now we have the following constraint on the model:

class MyClass(django_models.Model):
    ...
    fk_field = django_models.ForeignKey(to='myapp.OtherModel', on_delete=django_models.CASCADE, related_name='myclasses')
    char_field = django_models.CharField(max_length=255, blank=True)
    ...
    class Meta:
        constraints = [
            django_models.UniqueConstraint(
                fields=['fk_field', 'char_field'], condition=~django_models.Q(char_field=''), name='unique_fk_field_%(class)s_char_field'
            )
        ]

This setup is causing issues with ModelSerializer (without overriding extra_kwargs) for char_field as it becomes required.

The current setup explicitly allow '' (empty string) as default to be excluded from unique constraint. What is the approach to handle it? Should we manually add this using extra_kwargs or we can solve it the same way how https://github.com/encode/django-rest-framework/issues/9378 was solved?

We can add something like:

if unique_constraint_field.blank:
    default = ''

Am I missing something here?

NOTE: this is kind of a blocker for us to move forward from 3.14. If the decision will be to support it manually, then we have to update around 10 different places... or we can wait for the fix from library...

sshishov avatar Aug 02 '25 10:08 sshishov

Unfortunately this issue cannot be solved using extra_kwargs as the unique_constraint's required is added after it:

        # Determine any extra field arguments and hidden fields that
        # should be included
        extra_kwargs = self.get_extra_kwargs()
        extra_kwargs, hidden_fields = self.get_uniqueness_extra_kwargs(
            field_names, declared_fields, extra_kwargs
        )

In order to fix this issue for us, we have to COMPLETELY OVERRIDE the field on serializer, which is making development and keeping fields for model and serializer in-sync a huge efforts.

We should support such case, I do not know why people does not complain about this case? Nobody using UniqueTogether with CharFields?

sshishov avatar Aug 02 '25 12:08 sshishov

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Oct 18 '25 06:10 stale[bot]