gpt4 book ai didi

python - 使用声明性语法,如何定义表示多对一集合中最新对象的关系?

转载 作者:行者123 更新时间:2023-12-01 06:07:02 24 4
gpt4 key购买 nike

我正在使用 SQLAlchemy 的声明性语法,并且我想指定一个提供集合中最新(最大主 id)元素的关系。我找到了这篇文章:How do I define a SQLAlchemy relation representing the latest object in a collection?但我在使用这种模式时遇到了困难,仅使用声明性创建子查询。任何指示或帮助将不胜感激!

总体思路:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base(bind=engine, metadata=metadata)

from sqlalchemy import *
from sqlalchemy.orm import *

class NewsPaper(Base):
__tablename__ = "newspapers"
id = Column(Integer, nullable=False, primary_key=True)
name = Column(String(255))
latest_article = relationship("Article",
primaryjoin="(Article.newspaper_id==NewsPaper.id) &"
"(Article.id==SUBQUERY_FOR_LATEST_ID)")
def __repr__(self):
return '''<name={0}>'''.format(self.name)


class Article(Base):
__tablename__ = "articles"
id = Column(Integer, nullable=False, primary_key=True)
title = Column(String(255))
newspaper_id = Column(Integer, ForeignKey('newspapers.id'))
newspaper = relationship("NewsPaper", backref=backref('articles') )

def __repr__(self):
return '''<title={0}>'''.format(self.title)

最佳答案

最简单的方法是在定义所有类后在类外部定义关系
NewsPaper 中删除 latest_article 的定义,并在 class Article 定义之后添加以下代码(直接取自您链接到的 Mike 的答案):

# define the relationship
t_article = Article.__table__
t_newpaper = NewsPaper.__table__
latest_c = (select([t_article.c.id]).
where(t_article.c.newspaper_id == t_newpaper.c.id).
order_by(t_article.c.id.desc()).
limit(1).
correlate(t_newpaper).
as_scalar()
)
NewsPaper.latest_article = relationship("Article",
primaryjoin=and_(
t_article.c.id==latest_c,
t_article.c.newspaper_id==t_newpaper.c.id,
),
uselist=False
)

但需要注意的是:该关系直接作用于数据库,因此它不会包括那些尚未提交但属于该数据库一部分的 Article 实例。 session 。而且很可能它们就是您真正想要的。所以要小心一点。

关于python - 使用声明性语法,如何定义表示多对一集合中最新对象的关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7521715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com