此示例来自Django documentation。
给出(Django)数据库模型:
class Blog(models.Model):
name = models.CharField(max_length=100)
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
在Django我可以使用:
Entry.objects.filter(blog__name__exact='Beatles Blog')
获取具有指定名称的博客的所有Entry
个对象。
问题:在给定下面的模型定义的情况下,等效的SQLAlchemy语句是什么?
class Blog(Base):
__tablename__ = "blog"
id = Column(Integer, primary_key=True)
name = Column(Unicode(100))
class Entry(Base):
__tablename__ = "entry"
id = Column(Integer, primary_key=True)
blogid = Column(Integer, ForeignKey(Blog.id))
headline = Column(Unicode(255))
body_text = Column(UnicodeText)
blog = relationship(Blog, backref="entries")
修改
我相信有两种方法可以实现这一目标:
>>> q = session.query
>>> print q(Entry).join(Blog).filter(Blog.name == u"One blog")
SELECT entry.id AS entry_id, entry.blogid AS entry_blogid, entry.headline AS entry_headline, entry.body_text AS entry_body_text
FROM entry JOIN blog ON blog.id = entry.blogid
WHERE blog.name = ?
>>> print q(Entry).filter(Entry.blog.has(Blog.name == u"One blog"))
SELECT entry.id AS entry_id, entry.blogid AS entry_blogid, entry.headline AS entry_headline, entry.body_text AS entry_body_text
FROM entry
WHERE EXISTS (SELECT 1
FROM blog
WHERE blog.id = entry.blogid AND blog.name = ?)
# ... and of course
>>> blog = q(Blog).filter(Blog.name == u"One blog")
>>> q(Entry).filter(Entry.blog == blog)
还有一些问题:
session.query(Entry).filter(Entry.blog.name == u"One blog")
,那会不会有意义吗?答案 0 :(得分:1)
怎么样:
session.query(model.Entry).join((model.Blog, model.Entry.blogid==model.Blog.id)).filter(model.Blog.name=='Beatles Blog').all()
答案 1 :(得分:1)
已经迟到了,但我偶然发现了这个:
https://github.com/mitsuhiko/sqlalchemy-django-query/blob/master/sqlalchemy_django_query.py
这会尝试使用django表示法构建查询。
来自文档:TabComponent
答案 2 :(得分:1)
我也一直梦想有类似Django"魔术加入"。我熟悉
sqlalchemy-django-query
它,我发现它对我的任务来说不够强大。
这就是我创作的原因 的 https://github.com/absent1706/sqlalchemy-mixins#django-like-queries 即可。
它与sqlalchemy-django-query
类似,但有更多其他功能(here's a comparison)。它也经过了充分的测试和记录。