Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique if not null SQLAlchemy and Django

Given this simple table written in SQLAlchemy and Django models.py, how would I set UPC to be unique if not null. UPC won't be available for all items, but if is it should be unique.

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)  

And

class Products(models.Model):
    id = models.AutoField(primary_key=True)
    product_name = models.TextField()
    upc = models.TextField(null=True, blank=True)
like image 668
MCH Avatar asked Sep 17 '12 09:09

MCH


1 Answers

Multiple rows with NULL values should not be a problem for the unique constraint. Only "values" must be unique, NULL is no value.

Have you tried?:

upc = Column(String(), unique=True, nullable=True) 
like image 55
Florian Avatar answered Oct 31 '22 02:10

Florian