从Peewee Join中的中间表中选择一列

时间:2015-09-01 18:43:57

标签: python mysql peewee

我正在使用Peewee创建一个应用程序。我有一个查询返回用户对象,这些对象通过表关系上的多对多关系链接到当前用户。在联系人查询中,我想选择“已确认”#39;来自Relationship的列以某种方式与每个User对象并排,以便我可以在列表中返回该信息。

class Entity(BaseModel):
    image = CharField(null=True)
    isgroup = IntegerField(db_column='isGroup')
    name = CharField()

    class Meta:
        db_table = 'Entities'

class Relationship(BaseModel):
    confirmed = IntegerField()
    entitya = ForeignKeyField(db_column='entityA', rel_model=Entity, to_field='id')
    entityb = ForeignKeyField(db_column='entityB', rel_model=Entity, related_name='Entities_entityb_set', to_field='id')

    class Meta:
        db_table = 'Relationships'

class User(BaseModel):
    activated = IntegerField()
    attributes = TextField()
    email = CharField()
    entity = ForeignKeyField(db_column='entityID', primary_key=True, rel_model=Entity, to_field='id')
    lastaccess = DateTimeField(db_column='lastAccess')
    password = CharField()
    signupdate = DateTimeField(db_column='signupDate')

    class Meta:
        db_table = 'Users'

    def contacts(self):
        contacts = []
        requested = User.select(User, Entity).join(Relationship, on=(User.entity == Relationship.entitya)).join(Entity, on=Relationship.entitya).where(Relationship.entityb == self.entity, Entity.isgroup == False)
        requests = User.select(User, Entity).join(Relationship, on=(User.entity == Relationship.entityb)).join(Entity, on=Relationship.entityb).where(Relationship.entitya == self.entity, Entity.isgroup == False)
        for u in requested:
            contacts += [u]
        for u in requests:
            contacts += [u]
        return contacts

0 个答案:

没有答案