peewee一对多作为收藏品

时间:2018-04-29 21:13:12

标签: python sqlite flask orm peewee

我想用Pewee / Python3实现这样的模型。 有一些用户需要将消息发布到不同的渠道。 因此,必须有两个表:频道用户。如果简化,它看起来像:

渠道
PK channel_id: int
   channel_name: string
   title: string

用户
PK user_id: int
   user_name: string
FK频道:频道列表

我想它看起来应该是这样的:

class Channel(BaseModel):
    channel_id = PrimaryKeyField()
    user = ForeignKeyField(User, backref='user')
    channel_name = CharField()
    title = CharField()


class User(BaseModel):
    user_id = PrimaryKeyField()
    user_name = CharField()
    title = CharField()
    channels = ForeignKeyField(Channel, backref='channels', null=True)

我希望它可以像普通的python列表一样访问,比如

some_user.channels.add(sample_channel)
...
for channel in some_user.channels:
    ...

等。 但我无法将 User.channels 用作集合。 如何使用Peewee实现它?

1 个答案:

答案 0 :(得分:0)

这是一种多对多的关系:

class Channel(Model):
    name = CharField()

class User(Model):
    username = CharField()

class UserChannel(Model):
    user = ForeignKeyField(User, backref='user_channels')
    channel = ForeignKeyField(Channel, backref='channel_users')

# get channels for a user named 'huey'
huey_channels = (Channel
                 .select()
                 .join(UserChannel)
                 .join(User)
                 .where(User.username == 'huey'))