[英]Can unique_together avoid nulls in Django
我使用 django 和 Sql server 作為數據庫。 我有一個使用unique_together
帶有多個主鍵的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
為空時添加此表的對象時,它不起作用,因為我將有一個重復的鍵。
我的問題是如何避免空值。
謝謝
你試過這個嗎?
class Meta:
constraints = [
models.UniqueConstraint(fields=['userid', 'fk_str'], name='name of constraint'),
models.UniqueConstraint(fields=['useridtmp', 'fk_str'], name='another name of constraint')
]
由於您的 ForeignKey 字段中有 null=True 和 blank=True ,因此 db 存儲空值是合理的。
如果在任何情況下,兩個 ForeignKey 都不應該為 null,則可以將 null 和 blank 標記為 false。 只需將它們從字段設置中刪除即可,因為它們默認設置為 false。 您可能需要重新創建數據庫才能使新設置生效。
然后, unique_together 不會有空值問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.