michiya / django-pyodbc-azure

Django backend for Microsoft SQL Server and Azure SQL Database using pyodbc
https://pypi.python.org/pypi/django-pyodbc-azure
BSD 3-Clause "New" or "Revised" License
321 stars 140 forks source link

Add support for nullable unique constraints #184

Open OskarPersson opened 6 years ago

OskarPersson commented 6 years ago

This is similar to #43, #69 and #144, and probably fixes #14.

Unlike the other PRs which are for Django 1.9 and 2.0, this is for 1.11 but should be easy to at least Django 2.x.

Unlike #144, no migrations fail when running the Django tests. Having the constraints not apply to m2m-fields solved that issue.

OskarPersson commented 6 years ago

Somehow I managed to only include m2m-fields instead of the other way around, this is fixed in the latest commit.

However, this results in the same error as in #144 to occur, though this doesn't seem possible to avoid in SQL Server. The error that occurs is because of these models defined in the django test suite:

class Car(models.Model):
    make = models.CharField(max_length=20, unique=True, null=True)
    drivers = models.ManyToManyField('Driver', through='CarDriver')

class Driver(models.Model):
    name = models.CharField(max_length=20, unique=True, null=True)

class CarDriver(models.Model):
    car = models.ForeignKey('Car', models.CASCADE, to_field='make')
    driver = models.ForeignKey('Driver', models.CASCADE, to_field='name')

CarDriver.car references the make field in the Car model. Since the make field is defined to be unique and null, and we remove the UNIQUE string from the definition an error occurs from SQL Server since we want to reference a column that is not guaranteed to be unique. (Even though we create the filtered nullable constraint).

This is probably as good as it gets with nullable unique constraints using the currently available features of SQL Server

n2ygk commented 5 years ago

This would be really helpful. I tried working around this with a migration that replaces OneToOneField with ForeignKey and uses RunSQL to create the "unique index where ... is not null" but that change in the migration gets flagged as a model change. This is a much better fix.

ZippoLag commented 5 years ago

Hi, is anyone working on porting this for v2 by any chance?

OskarPersson commented 5 years ago

We are using this in a fork here https://github.com/ESSolutions/django-mssql-backend (PyPi: https://pypi.org/project/django-mssql-backend/)