Unique_together可以避免在Django中返回null

问题描述 投票:0回答:1

我正在使用django和Sql Server作为数据库。我有一个带有多个主键的表,使用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'))

所以当我在useridtmp为null时添加此表的对象时,它将不起作用,因为我将有重复的键。

我的问题是如何避免使用空值。

谢谢

python sql-server django django-2.0
1个回答
0
投票

您尝试过这个吗?

 class Meta:
        constraints = [
            models.UniqueConstraint(fields=['userid', 'fk_str'], name='name of constraint'),
            models.UniqueConstraint(fields=['useridtmp', 'fk_str'], name='another name of constraint')
        ]
© www.soinside.com 2019 - 2024. All rights reserved.