簡體   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