Can unique_together avoid nulls in Django

551 Views Asked by At

I am using django and Sql server as a database. I have a table with a multiple primary key using the unique_together

class Attribute_tmp(models.Model):
    useridtmp = models.ForeignKey(User_tmp, on_delete=models.CASCADE, blank =True, null = True)
    userid = models.ForeignKey(User, on_delete=models.CASCADE, blank =True, null = True)
    fk_str = models.ForeignKey(Stream, on_delete=models.CASCADE)
    class Meta:
            unique_together = (('userid', 'fk_str'),('useridtmp', 'fk_str'))

So when i add objects of this table when the useridtmp is null, it doesn't work because i will have a duplicated key.

My Question is how can i avoid the null values.

Thank you

2

There are 2 best solutions below

0
Rafael Ribeiro On

Did you tried this?

 class Meta:
        constraints = [
            models.UniqueConstraint(fields=['userid', 'fk_str'], name='name of constraint'),
            models.UniqueConstraint(fields=['useridtmp', 'fk_str'], name='another name of constraint')
        ]
2
Jun Zhou On

Since you have null=True and blank=True in your ForeignKey field, it is reasonable for db to store null values.

If in any case, the two ForeignKeys shouldn't be null, you can mark null and blank as false. Simply removing them from field settings will do the trick as they are set to false by default. You probably need to recreate the database to make the new settings working.

Then, the unique_together will not have an issue with null values.