【问题标题】:Can unique_together avoid nulls in Djangounique_together 可以避免 Django 中的空值吗
【发布时间】:2020-06-19 09:30:51
【问题描述】:

我使用 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 为空时添加此表的对象时,它不起作用,因为我将有一个重复的键。

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

谢谢

【问题讨论】:

    标签: python sql-server django django-2.0


    【解决方案1】:

    你试过了吗?

     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】:

      由于您的 ForeignKey 字段中有 null=True 和 blank=True,因此 db 存储 null 值是合理的。

      如果在任何情况下,两个 ForeignKey 不应该为 null,您可以将 null 和空白标记为 false。只需将它们从字段设置中删除即可,因为它们默认设置为 false。您可能需要recreate the database 才能使新设置生效。

      那么,unique_together 不会有空值的问题。

      【讨论】:

      • 感谢您的回答,但我无法进行此更改,因为有时我有空值
      • 在这种情况下,您可能需要其他方法来防止用户输入“空值”(表单端)而不是“空值”(数据库端)。这可以在您的表单验证中完成,也可以使用serializer 和make the field required in meta class。
      猜你喜欢
      • 2011-10-08
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2010-10-01
      相关资源
      最近更新 更多