Bohdan Popovych
Bohdan Popovych

Reputation: 35

peewee one-to-many as collection

I want to implement such a model with Pewee/Python3. There is a users, who need to post messages into different channels. So, there must be two tables: channels and users. If simplified, it looks like that:

channels
PK channel_id: int
channel_name: string
title: string

users
PK user_id: int
user_name: string
FK channels: list of channels

I suppose It should look like that:

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)

And I want it to be accessible as a common python list, like

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

etc. But I am unable to use User.channels as a collection. How can I implement it using Peewee?

Upvotes: 0

Views: 2917

Answers (1)

coleifer
coleifer

Reputation: 26235

This is a many-to-many relationship:

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

Upvotes: 2

Related Questions