4👍
I came across the same issue and fixed it by specifying None
for the field when saving.
Specifying default=None
could be helpful as well.
👤SaeX
3👍
Django supports creating unique constraints that have conditions. A custom constraint can be created that enforces uniqueness for a given field only under the condition that a field’s value is not blank.
from django.db.models import Q
serialnumber_is_not_blank = ~Q(serial_number="")
class Meta:
constraints = [
models.UniqueConstraint(
fields=["serial_number"],
condition=serialnumber_is_not_blank,
name="unique_serial_number",
)
]
👤jnns
- PyCharm remote debugging – connects but can't start debugging
- I am getting no module name cleo when trying to do "poetry add"
- Query a template for the variables it needs?
- Saving Python Pickled objects in MySQL db
- Where is the ON DELETE CASCADE logic being implemented in Django? (PostgreSQL is used)
-1👍
I’m pretty sure that having null values aren’t taken into account in uniqueness constraints. The way to get around this is to not use null, but instead use an empty string. So, remove null=True
.
- Haystack search results: how to use different templates for different models in page.object_list?
- Python split url to find image name and extension
- Django: When to run makemigrations?
- Django does not send csrf token again after browser cookies has been cleared
Source:stackexchange.com