皮威 one-to-many 作为 collection

peewee one-to-many as collection

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

渠道
PK channel_id: int
channel_name: 字符串
标题:字符串

用户
PK user_id: int
user_name: 字符串
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 用作 collection。 我如何使用 Peewee 实现它?

这是多对多关系:

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