简体   繁体   中英

In SQLAlchemy, how can I make this conditional query on a child relationship?

I want to make a query like this (I'm not sure how it would look even in SQL, so I might be totally off base on whether this is even possible):

Given:

class Parent(Base):
    __tablename__ = 'parent'
    __table_args__ = {
        UniqueConstraint("name", "version")
        }

    name = Column(String, primary_key=True)
    parent = Column(JSONEncodedDict)
    tags = relationship(ParentTags)
    version = Column(Integer)

class ParentTags(Base)::

    __tablename__ = 'parent_tags'
    __table_args__ = {
        UniqueConstraint("name", "tag"),
        }

    id = Column(Integer, Sequence("parent_tag_id_seq"), primary_key=True)
    name = Column(String, ForeignKey("parent.name"))
    tag = Column(String)
    version = Column(Integer)

I want these queries:

  1. All parents by named version; if I ask for a named version "Production", then only the Parent name,version tuples where version is in the tags table with tag = "Production".

  2. All parents by named version with default to the latest; If I ask for a version named "Production", then if a named Parent has a "Production" version is present, return that; if not, return the maximum version.

  3. A specific parent, by version, falling back to the latest if no such version exists.

I'm using SQLAlchemy 0.7.4, which gives me the newest as far as I know. Any suggestions are welcome.

Ans 1 :

session.query(Parent.name, Parent.version).\
              join(ParentTag).\
              filter(ParentTag.tag=='Production').\
              all()

I am little confuse in description 2 and 3. Please give some details with example if first ans is work for you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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