2012-09-17 23 views
7

鑑於使用SQLAlchemy和Django models.py編寫的這個簡單表,如果將UPC設置爲唯一(如果不爲null),我該如何設置它。 UPC將不可用於所有項目,但如果它是唯一的。唯一(如果不爲空)SQLAlchemy和Django

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) 

回答

7

具有NULL值的多行不應該是唯一約束的問題。只有「值」必須是唯一的,NULL是沒有價值的。

你有沒有試過?:

upc = Column(String(), unique=True, nullable=True) 
+2

好吧,這是有道理的。我意識到我可能在應用程序中的某個地方犯了一個錯誤,但我實際上可能會放置一個空字符串,這會導致唯一性問題。 – MCH