代码之家  ›  专栏  ›  技术社区  ›  EsotericVoid

SQLAlchemy:设计具有唯一性约束的多对多关系

  •  0
  • EsotericVoid  · 技术社区  · 8 年前

    我试图在我的模型中设计这两个实体之间的关系:
    A. Lick 是一个有序的序列 Note s(作为回报,可以是不同舔的一部分),因此我决定在关联类中使用position字段实现多对多。我想为我的Lick类添加一个惟一的约束,以避免重复,但我不知道如何以ORM的方式来实现。我提出的唯一解决方案是在Lick类中设置一个自定义id字段(而不是通常的增量整数),我确信该字段是唯一的,但我觉得我基本上是在用字符串重新编码数据库中已经存在的内容。有没有办法在Lick类中设置一个与音符顺序相关的唯一字段?

    提前谢谢。下面您可以看到我的模型:

    class LickNote(db.Model):
        __tablename__ = 'lick_note'
        __table_args__ = (
            db.ForeignKeyConstraint(('note_string', 'note_fret', 'note_value'),
                                    ('note.string', 'note.fret', 'note.value')),
        )
        lick_id = db.Column(db.String, db.ForeignKey('lick.id'), primary_key=True)
        note_string = db.Column(db.Integer, primary_key=True)
        note_fret = db.Column(db.Integer, primary_key=True)
        note_value = db.Column(db.Integer, primary_key=True)
        position = db.Column(db.Integer)
        notes = db.relationship("Note")
    
    
    class Lick(db.Model):
        """
        A lick is identified as a sequence of notes. The identifier is a string in this form:
        ssffvvssffvv.....ssffvv, where ss refers to the string (00-12), ff to the fret (00-23) and vv to the value of the
        note (00-11). This sequence is guaranteed to be unique 
        """
        __tablename__ = 'lick'
    
        id = db.Column(db.String, primary_key=True)
        notes = db.relationship("LickNote")
    
    
    
    class Note(db.Model):
        """
        Value represents the int conversion of the note [0,11]. Marked as primary to identify the possibility of having
        different tunings for the same position on the fretboard
        """
        __tablename__ = 'note'
    
        string = db.Column(db.Integer, primary_key=True)
        fret = db.Column(db.Integer, primary_key=True)
        value = db.Column(db.Integer, primary_key=True)
    
    0 回复  |  直到 8 年前