如何在peewee中使用CompositeKey和ForeignKeyField

时间:2017-11-30 14:02:40

标签: python sqlite peewee

我无法弄清楚如何在表之间添加关系。

 heroku run python manage.py migrate

我想保证MyModel中的'a','b','c','d'字段创建独特的组合。 (独一无二)

我还想将此表RModel表的关系添加为ForeignKey

我还在

class MyModel(BaseModel):
    a = peewee.TextField()
    b = peewee.TextField()
    c = peewee.IntegerField()
    d = peewee.TextField()
    e = peewee.FloatField()
    f = peewee.FloatField()

    class Meta:
        primary_key = peewee.CompositeKey('a', 'b', 'c', 'd')


class RModel(BaseModel):
    """
    """
    record = peewee.ForeignKeyField(MyModel, related_name='record')
    date = peewee.DateTimeField(default=datetime.datetime.now)

1 个答案:

答案 0 :(得分:0)

Peewee不支持复合外键。你想做这样的事情:

class RModel(BaseModel):
    a = peewee.TextField()
    b = peewee.TextField()
    c = peewee.IntegerField()
    d = peewee.TextField()

    class Meta:
        constraints = ['...(optional) sql for constraint...']

    @property
    def my_model(self):
        return MyModel.get(
            (MyModel.a == self.a) &
            (MyModel.b == self.b) &
            (MyModel.c == self.c) &
            (MyModel.d == self.d))