Ticket #10244 - FileField can't be set to NULL in the database

I’m seeking consensus and guidance on how to proceed with Ticket #10244.

My personal leaning is to agree with the second option that Aymeric Augustin offered: Make FileField behave exactly like CharField with regard to null. This would allow actual null values in the database for FileFields instead of empty strings. Are the implications to backward-compatibility acceptable?

I would like to work on this ticket if a consensus can be reached and the current owner is no longer interested.

Ugh, what a mess! I think we should bite the bullet and make backwards incompatible changes to make this sensible in the long term. If we can do this with deprecations to minimise the impact, so much the better.

1 Like

If we can do this with deprecations to minimise the impact, so much the better.

I believe that one way to achieve that would be to have None resolve to a deprecation period only NoneFieldFile instance (instead of directly to None) that raises deprecation warnings when accessing .name and .path and has a __bool__ -> False.

While we won’t be able to have deprecation warnings point at using model_instance.field_field is None gates they should be able to use if model_instance.file_field and prepare for the eventuality of it returning None in future versions.

NoneFieldFile could then be turned back into None at persistence time and eventually be removed altogether.

1 Like

This sounds like a good idea, thanks! I can start prototyping this approach.

Are there any other opinions?

Aligning FileField with CharField for null values sounds logical. The NoneFieldFile idea is a smart way to ensure smooth deprecation. Excited to see this improvement.

Thanks for the feedback! I’ll start prototyping this.

1 Like

The current situation is indeed a mess as best described here. It would be interesting to understand what the motivation was behind returning a “fake” [Field]File that has a name "" and raises a ValueError when trying to open() it, instead of just None?

I will add that “Aligning FileField with CharField for null values sounds logical.” doesn’t sound right to me. While for TextField/CharField you have legitimate cases where it makes sense to differentiate between an empty string and None/null, a "" will never be a valid path/url (same as it won’t be a valid date or integer). So I’d say it makes more sense to align it with DateField/IntegerField.

Oh and also, fwiw, subclassing FileField and translating between "" and None in from_db_value/get_prep_value seems to work OK to at least have a clean database representation.