我有一个这样的模型
class ProductCode( models.Model):
class Meta:
unique_together=[('code','customer'), ]
customer = models.ForeignKey( 'customers.Customer', models.CASCADE, null=True, blank=True, )
code = models.CharField( max_length = 20)
product = models.ForeignKey( Product, models.CASCADE, )
...
问题是,如果为customer is None
(DB NULL),则不会强制执行约束.它允许我多次使用(code=‘foo’,Customer=None)存储行/对象.我找到了this SO post个,这表明这个问题对于postgres用户来说是无法修复的.
有没有办法在(相对)较新的Meta
constraints
中强制执行这一限制?我发现the documentation有点难理解.
或者,我必须实现一个占位符客户来附加"默认"产品代码吗?
或者,另一种方法是在文本表示法前面加上customer
到code
,然后将其设置为unique=True
,并在必要时使用__startswith=
和__contains
查找.