繁体   English   中英

Peewee - 轻松访问中间表

[英]Peewee - Access an intermediary table easily

假设我有这样的peewee模型:

class Users(_BaseModel):
    id = AutoField(primary_key=True, null=False, unique=True)

    first_name = CharField(null=False)
    last_name = CharField(null=False)
    # Cut short for clarity

class Cohorts(_BaseModel):
    id = AutoField(primary_key=True, null=False, unique=True)
    name = CharField(null=False, unique=True)
    # Cut short for clarity

class CohortsUsers(_BaseModel):
    cohort = ForeignKeyField(Cohorts)
    user = ForeignKeyField(Users)
    is_primary = BooleanField(default=True)

我需要从用户那里轻松访问他们所在的群组,例如群组的名称。 如果一个用户只能在一个群组中,那会很容易,但在这里,如果它是 many2many 会使事情变得复杂。

这是我到目前为止所得到的,这非常丑陋且效率低下

Users.select(Users, CohortsUsers).join(CohortsUsers).where(Users.id == 1)[0].cohortsusers.cohort.name

这将满足我的要求,但我想找到一种更好的方法来做到这一点。

有没有办法让我可以做Users.get_by_id(1).cohort.name

编辑:我正在考虑在我的Users类上轻松访问它们的方法,但我不确定这是最好的方法,也不知道如何去做

如果它这样做,它是相当难看的,因为方法内部的导入以避免循环导入

@property
def cohort(self):
    from dst_datamodel.cohorts import CohortsUsers
    return Users.select(Users, CohortsUsers).join(CohortsUsers).where(Users.id == self.id)[0].cohortsusers.cohort

但是拥有这种ugly的方法让我可以轻松地做Users.get_by_id(1).cohort

这在此处的文档中都有介绍:http: //docs.peewee-orm.com/en/latest/peewee/relationships.html#implementing-many-to-many

您有一个多对多关系,其中一个用户可以在零个、一个或多个群组中,而一个群组可能有零个、一个或多个用户。

如果存在用户只有一个群组的不变量,那么只需执行以下操作:

# Get all cohorts for a given user id and print their name(s).
q = Cohort.select().join(CohortUsers).where(CohortUsers.user == some_user_id)
for cohort in q:
    print(cohort.name)

更具体到您的示例:

@property
def cohort(self):
    from dst_datamodel.cohorts import CohortsUsers
    cohort = Cohort.select().join(CohortsUsers).where(CohortUsers.user == self.id).get()
    return cohort.name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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