FileField null=True unique=True

Seems like FileField / ImageField cannot have null=True + unique=True
I’m testing this on sqlite and I get IntegrityError: UNIQUE constraint failed for multiple rows without a file.
FieldFile seems to always save empty string to the db, even when I do foo.objects.create(file=None)

Shouldn’t this behavior be mentioned in the docs? I can’t find it anywhere

I guess the simplest solution then is null=False + blank=True +

UniqueConstraint(
    fields=["file"],
    condition=~Q(file=""),
    name="unique_non_empty_file",
)

(if you’re not using MySQL)

There was a discussion about this just over a year ago, about a bug that’s been unresolved for 17 years now.

On the plus side, at least you’re not alone :slight_smile:

Aha, I didn’t find it, thanks!

This behavior is a common gotcha with Django’s FileField and ImageField. Since empty values are stored as empty strings instead of NULL, the unique constraint conflict on SQLite makes sense. A conditional UniqueConstraint is usually the cleanest workaround.