过滤关系

时间:2015-10-29 12:12:43

标签: python sqlalchemy

我正在尝试过滤关系。在我的数据库中,我有奖项和奖项类别。我想只检索特色而非提名奖。

这是我的模特:

class AwardsAwardsCategory(Base):
    __tablename__ = 'awards_awards_categories'
    id = Column(Text, primary_key=True, default=generate_unique_id)
    awards = relationship("Award")
    award_id = Column(Text, ForeignKey("awards.id", ondelete='cascade'))
    nomination = Column(Boolean)

    def __json__(self, request):
        return {
            "id": self.id,
            "nomination": self.nomination
        }


class Award(Base):
    __tablename__ = 'awards'
    id = Column(Text, primary_key=True, default=generate_unique_id)
    type = Column(Text)
    featured = Column(Integer)
    awards = relationship("AwardsAwardsCategory", lazy='joined')

    def __json__(self, request):
        return {
            "id": self.id,
            "type": self.type,
            "number_of_awards": len(self.awards),
            "featured": self.featured,

        }

这是我的电话:

    query = self.session.query(Award)
    query = query.join(AwardsAwardsCategory.awards)
    query = query.filter(Award.featured != 0)
    query = query.filter(AwardsAwardsCategory.nomination != True)
    q_results = query.all()

这导致以下查询:

SELECT awards.id AS awards_id, awards.type AS awards_type, awards.featured AS awards_featured, awards_awards_categories_1.id AS awards_awards_categories_1_id, awards_awards_categories_1.award_id AS awards_awards_categories_1_award_id, awards_awards_categories_1.nomination AS awards_awards_categories_1_nomination 
FROM awards_awards_categories JOIN awards ON awards.id = awards_awards_categories.award_id LEFT OUTER JOIN awards_awards_categories AS awards_awards_categories_1 ON awards.id = awards_awards_categories_1.award_id 
WHERE awards.featured != 0 AND awards_awards_categories.nomination != true 

除了WHERE子句缺少条件外几乎正确:

 AND awards_awards_categories_1.nomination != true

如何更改我的代码,以便将最后一个条件添加到WHERE子句中。

1 个答案:

答案 0 :(得分:0)

我最终过滤了应用层上的提名。它很讨厌,但它确实有效。

query = self.session.query(Award)
query = query.join(AwardsAwardsCategory.awards)
query = query.filter(Award.featured != 0)
query = query.filter(AwardsAwardsCategory.nomination != True)
q_results = query.all()

# remove all objects from the session in order to keep them in the db.
self.session.expunge_all()
for award_category in q_results:
    # keep a separate list of the awards, in order to keep the iteration going as desired
    awards = list(award_category)
    for award in award_category.awards:
        if award.nomination:
            awards.remove(award)
    def __json__(self, request):
        return {
             "id": self.id,
             "type": self.type,
             "number_of_awards": self.number_of_awards,
             "featured": self.featured,
        }
    award_category.number_of_awards = len(awards)
    award_category.__json__ = types.MethodType( __json__, a )

如果有人知道如何在SQLAlchemy中做得更好,请告诉我!