简体   繁体   中英

Can unique_together avoid nulls in Django

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

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')
        ]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM