以下代码:
Base = declarative_base()
engine = create_engine(r"sqlite:///" + r"d:\foo.db",
listeners=[ForeignKeysListener()])
Session = sessionmaker(bind = engine)
ses = Session()
class Foo(Base):
__tablename__ = "foo"
id = Column(Integer, primary_key=True)
name = Column(String, unique = True)
class Bar(Base):
__tablename__ = "bar"
id = Column(Integer, primary_key = True)
foo_id = Column(Integer, ForeignKey("foo.id"))
foo = relationship("Foo")
class FooBar(Base):
__tablename__ = "foobar"
id = Column(Integer, primary_key = True)
bar_id = Column(Integer, ForeignKey("bar.id"))
bar = relationship("Bar")
Base.metadata.create_all(engine)
ses.query(FooBar).filter(FooBar.bar.foo.name == "blah")
Run Code Online (Sandbox Code Playgroud)
给我这个错误:
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' …Run Code Online (Sandbox Code Playgroud) 当我尝试创建数据库模式迁移时,我遇到了这个奇怪的错误.你能帮我弄清楚出了什么问题吗?
$ python app.py db upgrade
[skipped]
sqlalchemy.exc.ArgumentError: Mapper Mapper|EssayStateAssociations|essay_associations could not assemble any primary key columns for mapped table 'essay_associations'
Run Code Online (Sandbox Code Playgroud)
我的模特:
class EssayStateAssociations(db.Model):
__tablename__ = 'essay_associations'
application_essay_id = db.Column(
db.Integer,
db.ForeignKey("application_essay.id"),
primary_key=True),
theme_essay_id = db.Column(
db.Integer,
db.ForeignKey("theme_essay.id"),
primary_key=True),
state = db.Column(db.String, default="pending")
Run Code Online (Sandbox Code Playgroud) 如何用sqlAlchemy调用sql server的存储过程?
sqlautocode - 存在多对多关系的问题
sqlsoup - 不支持关系
elixir - 它注意自动生成
还有什么我可以尝试的吗?
我正在尝试从我的数据集返回一个总计/平均行,其中包含某些字段的SUM和其他字段的AVG.
我可以在SQL中执行以下操作:
SELECT SUM(field1) as SumFld, AVG(field2) as AvgFld
FROM Rating WHERE url=[url_string]
Run Code Online (Sandbox Code Playgroud)
我将此转换为SQLAlchemy的尝试如下:
totals = Rating.query(func.avg(Rating.field2)).filter(Rating.url==url_string.netloc)
Run Code Online (Sandbox Code Playgroud)
但这是错误的:
TypeError: 'BaseQuery' object is not callable
Run Code Online (Sandbox Code Playgroud) 对,我已经看到了直接存储在主应用程序文件(机型瓶应用的许多例子http://pythonhosted.org/Flask-SQLAlchemy/quickstart.html,http://maximebf.com/blog/2012/10/建设网站-in-python-with-flask /).其他的(http://flask.pocoo.org/docs/patterns/sqlalchemy/)有一个"models.py"文件,其中放置了模型.
如何从单独的文件中取出我的Flask app导入模型,例如"User.py"?当我尝试使用这些内容创建User.py文件时:
from app import db
class User(db.Model):
[...]
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
File "/Users/stackoverflow/myapp/models/User.py", line 1, in <module>
from app import db
ImportError: No module named app
Run Code Online (Sandbox Code Playgroud)
当我插入from models import User我的模块文件.
我正在尝试使用带有SQLALchemy的参数(在一个alembic脚本中)运行这个简单的原始sql语句:
from alembic import op
t = {"code": "123", "description": "one two three"}
op.execute("insert into field_tags (id, field_id, code, description) "+
"values (1,'zasz', :code ,:description')", t)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
sqlalchemy.exc.StatementError: A value is required for bind parameter
'description' (original cause: InvalidRequestError: A value is required for
bind parameter 'description') "insert into field_tags (id, field_id, code,
description) values (1, 'math',
%(code)s ,%(description)s)" []
Run Code Online (Sandbox Code Playgroud)
解决方案:
t = {"code": "123", "description": "one two three"}
from sqlalchemy.sql import text
op.get_bind().execute(text("insert into field_tags (id, field_id, code, description) …Run Code Online (Sandbox Code Playgroud) python sqlalchemy database-migration flask-sqlalchemy alembic
这看起来似乎很有争议,但我刚刚通过了SQLAlchemy的ORM教程,最后得到了以下代码:
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///:memory:', echo=True)
metadata = MetaData()
users_table = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String),
Column('fullname', String),
Column('password', String)
)
metadata.create_all(engine)
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __init__(self, name, fullname, password):
self.name = name
self.fullname = fullname
self.password = …Run Code Online (Sandbox Code Playgroud) 假设我有一个表tags,其中有一个字段count,表示items已使用给定标签标记了多少.
在使用现有标记添加新项目后,如何在SQLAlchemy中增加此计数器?
使用纯SQL我会执行以下操作:
INSERT INTO `items` VALUES (...)
UPDATE `tags` SET count=count+1 WHERE tag_id=5
Run Code Online (Sandbox Code Playgroud)
但是我如何count=count+1在SQLAlchemy中表达?
谢谢,Boda Cydo.
我正在编写一个快速而脏的维护脚本来删除一些行,并希望避免从主项目中删除我的ORM类/映射.我有一个看起来类似于的查询:
address_table = Table('address',metadata,autoload=True)
addresses = session.query(addresses_table).filter(addresses_table.c.retired == 1)
Run Code Online (Sandbox Code Playgroud)
根据我读过的所有内容,如果我使用的是ORM(不是'只是'表)并传递了类似的内容:
addresses = session.query(Addresses).filter(addresses_table.c.retired == 1)
Run Code Online (Sandbox Code Playgroud)
我可以.delete()在查询中添加一个,但是当我尝试仅使用表格时,我会收到投诉:
File "/usr/local/lib/python2.6/dist-packages/sqlalchemy/orm/query.py", line 2146, in delete
target_cls = self._mapper_zero().class_
AttributeError: 'NoneType' object has no attribute 'class_'
Run Code Online (Sandbox Code Playgroud)
这是一个有意义的表,而不是一个类.在谈到SQLAlchemy时,我非常环保,我该怎么做呢?