peewee:多对多,设置多个ManyToManyField()

项目中需要一张表与多张表建立多对多的关系,因此就需要多个ManyToManyFild,下面提供一段测试程序供大家进行参考。

from peewee import *

database = SqliteDatabase('db.sqlite3')
class BaseModel(Model):
    class Meta:
        database = database

class User(BaseModel):
    username = CharField(unique=True)
    password = CharField()

TeacherThroughDeferred = DeferredThroughModel()
StudentThroughDeferred = DeferredThroughModel()

class Team(BaseModel):
    title = CharField()
    teachers = ManyToManyField(User, backref='lead_teams', through_model=TeacherThroughDeferred)
    students = ManyToManyField(User, backref='join_teams', through_model=StudentThroughDeferred)

class TeacherThrough(BaseModel):
    team = ForeignKeyField(Team)
    user = ForeignKeyField(User)

TeacherThroughDeferred.set_model(TeacherThrough)

class StudentThrough(BaseModel):
    team = ForeignKeyField(Team)
    user = ForeignKeyField(User)

StudentThroughDeferred.set_model(StudentThrough)

database.create_tables([
    User, Team,
    TeacherThrough,
    StudentThrough,
])

for k in range(10):
    usr = User()
    usr.username = f'Alex_{k}'
    usr.password = 'dsklf'
    try:
        usr.save()
    except:
        pass
team = Team()
team.title = "test"
team.save()
team.teachers.add([
    User.get(User.username == 'Alex_0'),
    User.get(User.username == 'Alex_1'),
    User.get(User.username == 'Alex_2'),
])
team.students.add([
    User.get(User.username == 'Alex_3'),
    User.get(User.username == 'Alex_4'),
    User.get(User.username == 'Alex_5'),
    User.get(User.username == 'Alex_6')
])
team.save()
for each in User.get(User.username == 'Alex_0').lead_teams:
    print(each)
print('-' * 20)
for each in User.get(User.username == 'Alex_3').join_teams:
    print(each)

 

你可能感兴趣的:(python,python,数据库,mysql)