10

鉴于这个用 SQLAlchemy 和 Django models.py 编写的简单表,如果不为空,我将如何将 UPC 设置为唯一的。UPC 不会适用于所有项目,但如果是的话,它应该是唯一的。

class Products(base):  
    __tablename__ = u'products'  
    id = Column(Integer(), primary_key=True, autoincrement = True)  
    product_name = Column(String(), unique=True, nullable=False)  
    upc = Column(String(), nullable = True)  

class Products(models.Model):
    id = models.AutoField(primary_key=True)
    product_name = models.TextField()
    upc = models.TextField(null=True, blank=True)
4

1 回答 1

12

具有 NULL 值的多行对于唯一约束不应该是问题。只有“值”必须是唯一的,NULL 是没有值的。

你有没有尝试过?:

upc = Column(String(), unique=True, nullable=True) 
于 2012-09-19T18:36:53.610 回答