2011-11-27 15 views
6
class PostsSubscribe(Base): 
    __tablename__ = 'posts_subscribe' 
    id = Column(Integer, primary_key = True) 
    post_id = Column(Integer, ForeignKey('posts_posts.id'), nullable=False) 
    persona_id = Column(Integer, ForeignKey('personas_personas.id'), nullable=False) 

    UniqueConstraint('post_id', 'persona_id') #this doesn't work. 
Base.metadata.create_all(engine) 

Bu, şu ana kadar benim masam. Gördüğünüz gibi tabloları tanımlamanın "Declorative" yöntemini kullanıyorum. Benzersiz bir anahtar oluşturmak istiyorum, ancak hattım çalışmıyor.SQLAlchemy'de, benzersiz bir çifti nasıl oluşturabilirim?

Benzersiz bir çifti nasıl oluştururum? Bir model sınıfı için değil, onun tablosu için olmalıdır.

cevap

11

. Bunu yapmak için __table_args__ yapabilirsiniz:

class PostsSubscribe(Base): 
    __tablename__ = 'posts_subscribe' 
    id = Column(Integer, primary_key = True) 
    post_id = Column(Integer, ForeignKey('posts_posts.id'), nullable=False) 
    persona_id = Column(Integer, ForeignKey('personas_personas.id'), nullable=False) 
    __table_args__ = (UniqueConstraint('post_id', 'persona_id', name='_person_post_uc'), 
        ) 
İlgili konular