Skip to content

Instantly share code, notes, and snippets.

@arlyon
Created April 8, 2018 11:07
Show Gist options
  • Save arlyon/0968168ab0a485658302417963d4bdea to your computer and use it in GitHub Desktop.
Save arlyon/0968168ab0a485658302417963d4bdea to your computer and use it in GitHub Desktop.
A Django foreign key that modifies None values to -1 so that the unique constraint in MySQL is respected.
class UniqueNullForeignKey(models.ForeignKey):
description = "Foreign Field that stores None as -1 to enforce the unique constraint."
def from_db_value(self, value, expression, connection, context):
"""
Intercepts the data being loaded and replaces -1 with None
for proper use in the application.
"""
return None if value == -1 else value
def to_python(self, value):
"""
Intercepts the data being loaded and replaces -1 with None
for proper use in the application.
"""
return None if value == -1 else value
def get_prep_value(self, value):
"""
Intercepts the data being saved and replaces None with -1
so that the unique constraint holds.
"""
return -1 if value is None else value
def get_db_prep_save(self, value, connection):
"""
Intercepts the data being saved and replaces None with -1
so that the unique constraint holds.
"""
return -1 if value is None else value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment