简体   繁体   中英

How to use CompositeKey and ForeignKeyField in peewee

I cannot figure out how to add relation between tables.

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)

I want to guaranteed that 'a', 'b', 'c', 'd' fields in MyModel create unique combination. (unique together)

I also would like to add relation to this table RModel table as ForeignKey

I am still getting

AttributeError: 'CompositeKey' object has no attribute 'get_db_field'

Peewee does not support composite foreign keys. You'll want to do something like this:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM