Hello I am trying to change a class in SQLAlchemy because it giving me an error, the error is:
File "<string>", line 2, in __init__
File "C:\Python34\lib\site-packages\sqlalchemy\orm\instrumentation.py", line 324, in _new_state_if_none
state = self._state_constructor(instance, self)
File "C:\Python34\lib\site-packages\sqlalchemy\util\langhelpers.py", line 725, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "C:\Python34\lib\site-packages\sqlalchemy\orm\instrumentation.py", line 158, in _state_constructor
self.dispatch.first_init(self, self.class_)
File "C:\Python34\lib\site-packages\sqlalchemy\event\attr.py", line 260, in __call__
fn(*args, **kw)
File "C:\Python34\lib\site-packages\sqlalchemy\orm\mapper.py", line 2693, in _event_on_first_init
configure_mappers()
File "C:\Python34\lib\site-packages\sqlalchemy\orm\mapper.py", line 2589, in configure_mappers
mapper._post_configure_properties()
File "C:\Python34\lib\site-packages\sqlalchemy\orm\mapper.py", line 1694, in _post_configure_properties
prop.init()
File "C:\Python34\lib\site-packages\sqlalchemy\orm\interfaces.py", line 144, in init
self.do_init()
File "C:\Python34\lib\site-packages\sqlalchemy\orm\relationships.py", line 1549, in do_init
self._process_dependent_arguments()
File "C:\Python34\lib\site-packages\sqlalchemy\orm\relationships.py", line 1605, in _process_dependent_arguments
self.target = self.mapper.mapped_table
File "C:\Python34\lib\site-packages\sqlalchemy\util\langhelpers.py", line 725, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "C:\Python34\lib\site-packages\sqlalchemy\orm\relationships.py", line 1535, in mapper
% (self.key, type(argument)))
sqlalchemy.exc.ArgumentError: relationship 'prod_comm_rel' expects a class or a mapper argument (received: <class 'sqlalchemy.sql.schema.Column'>)
But it never change the error keeps comming, this is my class:
class Product(Base):
__tablename__="xxxxxx_reg"
__table_args__ = {"useexisting": True}
id = Column("id",BIGINT, primary_key=True)
name = Column("_name",Text, nullable=False)
code = Column("code", BIGINT, unique=True)
status = Column("status",BIGINT, ForeignKey(Status.code),nullable=False)
description = Column("description",Text, nullable=False)
avatar = Column("avatar", Text, nullable=False)
type = Column("_type",BIGINT, ForeignKey(Type.id),nullable=False)
price = Column("price",Numeric(20,2),nullable=False)
costs = Column("costs",Numeric(20,2),default=0.00)
commCode = Column("commerce", BIGINT, ForeignKey(Commerce.code), nullable=False)
#Relation
prod_status_rel = relationship(Status, backref=backref("Product"))
prod_type_rel = relationship(Type, backref=backref("Product"))
prod_comm_rel = relationship(Commerce, backref=backref("Product"))
def __repr__(self):
return "<Product(id='%s', name='%s', status='%s', description='%s', " \
"type='%s', price='%s', costs='%s', code='%s',commerce='%s')>"%(self.id, self.name,
self.status,self.description,
self.type, self.price, self.costs, self.code, self.commCode)
metadata = MetaData()
product_tbl = Table(__tablename__, metadata,id,name,status,description, type,price, costs, code, commCode)
engine = conection().conORM()
metadata.create_all(engine)
How can I fix this code, because I made the change and when I run the class alone It works, the problem is when i try to run it with the other parts of the codes
Related
Basically on flask app server in models.py you use classes to call ORM on PostgreSQL however if you do one to one relations or one to many relationship. you can get a error if your do not defined your key as Unique. In postgresql all foreign keys must reference a unique key in the parent table, so in your bar table you must have a unique (name) index.Finally, we should mention that a foreign key must reference columns that either are a primary key or form a unique constraint.
Traceback (most recent call last):
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\sqlalchemy\engine\base.py", line 1248, in _execute_context
cursor, statement, parameters, context
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\sqlalchemy\engine\default.py", line 588, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "dicom"
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\lesli\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Users\lesli\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "D:\L_pipe\vessel_app_celery\vessel_env\Scripts\flask.exe\__main__.py", line 9, in <module>
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\flask\cli.py", line 990, in main
cli.main(args=sys.argv[1:])
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\flask\cli.py", line 596, in main
return super().main(*args, **kwargs)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\click\core.py", line 1062, in main
rv = self.invoke(ctx)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\click\core.py", line 1668, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\click\core.py", line 1668, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\click\core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\click\core.py", line 763, in invoke
return __callback(*args, **kwargs)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\click\decorators.py", line 26, in new_func
return f(get_current_context(), *args, **kwargs)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\flask\cli.py", line 440, in decorator
return __ctx.invoke(f, *args, **kwargs)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\click\core.py", line 763, in invoke
return __callback(*args, **kwargs)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\flask_migrate\cli.py", line 134, in upgrade
_upgrade(directory, revision, sql, tag, x_arg)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\flask_migrate\__init__.py", line 95, in wrapped
f(*args, **kwargs)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\flask_migrate\__init__.py", line 280, in upgrade
command.upgrade(config, revision, sql=sql, tag=tag)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\alembic\command.py", line 298, in upgrade
script.run_env()
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\alembic\script\base.py", line 489, in run_env
util.load_python_file(self.dir, "env.py")
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\alembic\util\pyfiles.py", line 98, in load_python_file
module = load_module_py(module_id, path)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\alembic\util\compat.py", line 184, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "migrations\env.py", line 96, in <module>
run_migrations_online()
File "migrations\env.py", line 90, in run_migrations_online
context.run_migrations()
File "<string>", line 8, in run_migrations
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\alembic\runtime\environment.py", line 846, in run_migrations
self.get_context().run_migrations(**kw)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\alembic\runtime\migration.py", line 520, in run_migrations
step.migration_fn(**kw)
File "D:\L_pipe\vessel_app_celery\Vessel-app\Back-end\migrations\versions\9ea0138f3052_.py", line 228, in upgrade
sa.PrimaryKeyConstraint('id')
File "<string>", line 8, in create_table
File "<string>", line 3, in create_table
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\alembic\operations\ops.py", line 1252, in create_table
return operations.invoke(op)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\alembic\operations\base.py", line 374, in invoke
return fn(self, operation)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\alembic\operations\toimpl.py", line 101, in create_table
operations.impl.create_table(table)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\alembic\ddl\impl.py", line 258, in create_table
self._exec(schema.CreateTable(table))
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\alembic\ddl\impl.py", line 140, in _exec
return conn.execute(construct, *multiparams, **params)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\sqlalchemy\engine\base.py", line 984, in execute
return meth(self, multiparams, params)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\sqlalchemy\sql\ddl.py", line 72, in _execute_on_connection
return connection._execute_ddl(self, multiparams, params)
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\sqlalchemy\engine\base.py", line 1046, in _execute_ddl
compiled,
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\sqlalchemy\engine\base.py", line 1288, in _execute_context
e, statement, parameters, cursor, context
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\sqlalchemy\engine\base.py", line 1482, in _handle_dbapi_exception
sqlalchemy_exception, with_traceback=exc_info[2], from_=e
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\sqlalchemy\util\compat.py", line 178, in raise_
raise exception
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\sqlalchemy\engine\base.py", line 1248, in _execute_context
cursor, statement, parameters, context
File "d:\l_pipe\vessel_app_celery\vessel_env\lib\site-packages\sqlalchemy\engine\default.py", line 588, in do_execut cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidForeignKey) there is no unique constraint matching given keys for referenced table "dicom"
[SQL:
CREATE TABLE "DicomFormData" (
id SERIAL NOT NULL,
session_id VARCHAR(200) NOT NULL,
date_uploaded TIMESTAMP WITHOUT TIME ZONE NOT NULL,
study_name VARCHAR(300) NOT NULL,
description VARCHAR(1000) NOT NULL,
PRIMARY KEY (id),
)
]
Solution
need to add table args with db.Unique Constraint
class Dicom(db.Model):
__tablename__ = 'dicom'
## data unqine id
__table_args__ = (
# this can be db.PrimaryKeyConstraint if you want it to be a primary key
db.UniqueConstraint('session_id'),
)
id = db.Column(db.Integer, primary_key=True)
date_uploaded = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
userReact_id = db.Column(db.Integer, db.ForeignKey('UserReact.id'), nullable=True)
dicom_stack = db.Column(db.LargeBinary, nullable=False)
thumbnail = db.Column(db.LargeBinary, nullable=False)
file_count = db.Column(db.Integer, nullable=True)
session_id = db.Column(db.String(200), nullable=False)
#uselist one to one relationship
formData = db.relationship('DicomFormData', uselist=True, backref='author', lazy=True)
def __repr__(self):
return f"Dicom('{self.date_uploaded}')"
class DicomFormData(db.Model):
id = db.Column(db.Integer, primary_key=True)
date_uploaded = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
study_name = db.Column(db.String(300), nullable=False)
description = db.Column(db.String(1000), nullable=False)
session_id = db.Column(db.String(200), db.ForeignKey('dicom.session_id'), nullable=False)
def __repr__(self):
return f"DicomFormData('{self.study_name}')"
I have this issue when I try to run upgrade on a migration that will change the type of a VARCHAR column to INTEGER and change the PK too. This is traceback:
The definition of the class is the follow:
class ActionsIntiza(Base):
__tablename__ = 'actions_intiza'
customer_user_id = sa.Column(sa.VARCHAR(20), nullable=False)
customer_id = sa.Column(sa.INTEGER(), primary_key=True, info={'sortkey': True})
intiza_action_created = sa.Column(sa.DATE(), nullable=False)
intiza_action = sa.Column(sa.VARCHAR(50), nullable=False)
intiza_action_type = sa.Column(sa.VARCHAR(50))
intiza_action_tag = sa.Column(sa.VARCHAR(50))
intiza_action_comment = sa.Column(sa.VARCHAR())
intiza_action_attachment = sa.Column(sa.VARCHAR(50))
moni_user_name = sa.Column(sa.VARCHAR(50))
The traceback:
Traceback (most recent call last):
File "C:\Users\Usuario\AppData\Roaming\Python\Python38\site-packages\sqlalchemy\sql\visitors.py", line 88, in _compiler_dispatch
meth = getter(visitor)
AttributeError: 'RedshiftDDLCompiler' object has no attribute 'visit_clause'
op.alter_column('actions_intiza', 'customer_id',
File "<string>", line 8, in alter_column
File "<string>", line 3, in alter_column
File "c:\users\usuario\appdata\local\programs\python\python38\lib\site-packages\alembic\operations\ops.py", line 1777, in alter_column
return operations.invoke(alt)
File "c:\users\usuario\appdata\local\programs\python\python38\lib\site-packages\alembic\operations\base.py", line 345, in invoke
return fn(self, operation)
File "c:\users\usuario\appdata\local\programs\python\python38\lib\site-packages\alembic\operations\toimpl.py", line 43, in alter_column
operations.impl.alter_column(
File "c:\users\usuario\appdata\local\programs\python\python38\lib\site-packages\alembic\ddl\postgresql.py", line 116, in alter_column
self._exec(
File "c:\users\usuario\appdata\local\programs\python\python38\lib\site-packages\alembic\ddl\impl.py", line 134, in _exec
return conn.execute(construct, *multiparams, **params)
File "C:\Users\Usuario\AppData\Roaming\Python\Python38\site-packages\sqlalchemy\engine\base.py", line 982, in execute
return meth(self, multiparams, params)
File "C:\Users\Usuario\AppData\Roaming\Python\Python38\site-packages\sqlalchemy\sql\ddl.py", line 72, in _execute_on_connection
return connection._execute_ddl(self, multiparams, params)
File "C:\Users\Usuario\AppData\Roaming\Python\Python38\site-packages\sqlalchemy\engine\base.py", line 1033, in _execute_ddl
compiled = ddl.compile(
File "<string>", line 1, in <lambda>
File "C:\Users\Usuario\AppData\Roaming\Python\Python38\site-packages\sqlalchemy\sql\elements.py", line 468, in compile
return self._compiler(dialect, bind=bind, **kw)
File "C:\Users\Usuario\AppData\Roaming\Python\Python38\site-packages\sqlalchemy\sql\ddl.py", line 29, in _compiler
return dialect.ddl_compiler(dialect, self, **kw)
File "C:\Users\Usuario\AppData\Roaming\Python\Python38\site-packages\sqlalchemy\sql\compiler.py", line 319, in __init__
self.string = self.process(self.statement, **compile_kwargs)
File "C:\Users\Usuario\AppData\Roaming\Python\Python38\site-packages\sqlalchemy\sql\compiler.py", line 350, in process
return obj._compiler_dispatch(self, **kwargs)
File "C:\Users\Usuario\AppData\Roaming\Python\Python38\site-packages\sqlalchemy\ext\compiler.py", line 436, in <lambda>
lambda *arg, **kw: existing(*arg, **kw),
File "C:\Users\Usuario\AppData\Roaming\Python\Python38\site-packages\sqlalchemy\ext\compiler.py", line 478, in __call__
return fn(element, compiler, **kw)
File "C:\Users\Usuario\AppData\Roaming\Python\Python38\site-packages\sqlalchemy\ext\compiler.py", line 425, in _wrap_existing_dispatch
raise exc.CompileError(
sqlalchemy.exc.CompileError: <class 'alembic.ddl.postgresql.PostgresqlColumnType'> construct has no default compilation handler.
Can you help me?
I'm building a flask app and I want to use sqlalchemy observers to update a shipment status once all products inside that shipment become available.
Here's my datamodel:
from app import db
from sqlalchemy_utils import observes
class Shipment(db.Model):
__tablename__ = 'shipment'
id = db.Column(db.Integer, primary_key=True)
products = db.relationship('Product', backref='shipment', lazy='dynamic')
all_products_ready = db.Column(db.Boolean)
#observes('products')
def product_observer(self, products):
for p in self.products:
if p.status != 'ready':
self.all_products_ready = False
return False
self.all_products_ready = True
return True
class Product(db.Model):
__tablename__ = 'product'
id = db.Column(db.Integer, primary_key=True)
shipment_id = db.Column(db.Integer, db.ForeignKey('shipment.id'))
status = db.Column(db.String(120), index=True)
And here is some code I run to test it:
shipment = models.Shipment(products=[models.Product(status='ready'), models.Product(status='not_ready')])
db.session.add(shipment)
db.session.commit()
print(shipment.all_products_ready)
When I run this code I get an InvalidRequestError: Session is already flushing.
Here is the stack trace:
Traceback (most recent call last):
File "test.py", line 5, in <module>
db.session.commit()
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy\orm\scoping.py",
line 150, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy\orm\session.py",
line 788, in commit
self.transaction.commit()
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy\orm\session.py",
line 384, in commit
self._prepare_impl()
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy\orm\session.py",
line 364, in _prepare_impl
self.session.flush()
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy\orm\session.py",
line 1985, in flush
self._flush(objects)
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy\orm\session.py",
line 2012, in _flush
self.dispatch.before_flush(self, flush_context, objects)
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy\event\attr.py", l
ine 221, in __call__
fn(*args, **kw)
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy_utils\observer.py
", line 272, in invoke_callbacks
for (root_obj, func, objects) in args:
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy_utils\observer.py
", line 252, in gather_callback_args
lambda obj: obj not in session.deleted
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy_utils\functions\o
rm.py", line 741, in getdotattr
last = [v for v in last if condition(v)]
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy\orm\dynamic.py",
line 245, in __iter__
sess = self.session
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy\orm\dynamic.py",
line 237, in session
sess.flush()
File "U:\dev\observertest\flask\lib\site-packages\sqlalchemy\orm\session.py",
line 1979, in flush
raise sa_exc.InvalidRequestError("Session is already flushing")
sqlalchemy.exc.InvalidRequestError: Session is already flushing
How can I use my models without getting this error?
I'm not completely sure why, but I think loading the relations using dynamic is causing problems here. In this line:
products = db.relationship('Product', backref='shipment', lazy='dynamic')
you need to change the lazy parameter to select instead of dynamic (or you can take out the lazy parameter alltogether as select is its default).
See the sqlalchemy reference for all the available options.
I'm trying to create following self-referencing EndpointsModel (the trick with _fix_up_properties() is taken from here: https://groups.google.com/forum/#!topic/appengine-ndb-discuss/1FmgEVK7JNM):
class EventFieldSchema(EndpointsModel):
name = ndb.StringProperty(required=True)
type = msgprop.EnumProperty(EventType, required=True)
EventFieldSchema.nested_fields = ndb.LocalStructuredProperty(EventFieldSchema,repeated=True)
EventFieldSchema._fix_up_properties()
This works for datastore model, but unfortunately, the nested_fields field won't be included into ProtoRPC message.
I've tried to manually specify message fields schema, by adding at the end following line:
EventFieldSchema._message_fields_schema = ('name', 'type', 'nested_fields')
but then app-engine fails, going into a loop, trying turn EventFieldSchema into ProtoRPC field:
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/main.py", line 3, in <module>
from er.api.event import EventRegistryApi
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/er/api/event.py", line 17, in <module>
class EventRegistryApi(remote.Service):
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/er/api/event.py", line 23, in EventRegistryApi
name='%s.insert' % RESOURCE_NAME)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/protorpc-1.0/protorpc/util.py", line 170, in positional_wrapper
return wrapped(*args, **kwargs)
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/model.py", line 1359, in method
kwargs[REQUEST_MESSAGE] = cls.ProtoModel(fields=request_fields)
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/model.py", line 1031, in ProtoModel
allow_message_fields=allow_message_fields)
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/model.py", line 969, in _MessageFields
proto_attr = to_proto(prop, field_index)
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/utils.py", line 137, in StructuredPropertyToProto
property_proto = property_proto_method()
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/model.py", line 1031, in ProtoModel
allow_message_fields=allow_message_fields)
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/model.py", line 969, in _MessageFields
proto_attr = to_proto(prop, field_index)
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/utils.py", line 137, in StructuredPropertyToProto
property_proto = property_proto_method()
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/model.py", line 1031, in ProtoModel
Is this a bug in EndpointsModel? What is the "proper" way of defining self-referencing EndpointsModels?
Having the same issue with self-referencing an EndpointsModel:
class UnitsProtoModel(EndpointsModel):
""" ProtoRPC Model for storing/retrieving a unit. """
_message_fields_schema = ('id', 'uic', 'parent_id', 'branch_id', 'name')
uic = ndb.StringProperty(required=True)
parent_id = ndb.StringProperty(required=True, default=None)
branch_id = ndb.StringProperty(required=True)
name = ndb.StringProperty(required=True)
abbreviated_name = ndb.StringProperty(default="")
flagged = ndb.BooleanProperty(default=False)
message = ndb.StringProperty(default="")
unit_created_at = ndb.DateTimeProperty(auto_now_add=True)
class UnitsCollection(EndpointsModel):
items = messages.MessageField(UnitsProtoModel, 1, repeated=True)
Error msg:
`File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine- default.bundle/Contents/Resources/google_appengine/lib/protorpc-1.0/protorpc/util.py", line 170, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/protorpc-1.0/protorpc/messages.py", line 1531, in init
raise FieldDefinitionError('Invalid message class: %s' % message_type)
FieldDefinitionError: Invalid message class:
UnitsProtoModel<abbreviated_name=StringProperty('abbreviated_name', default=''), branch_id=StringProperty('branch_id', required=True), flagged=BooleanProperty('flagged', default=False), message=StringProperty('message', default=''), name=StringProperty('name', required=True), owner=UserProperty('owner'), parent_id=StringProperty('parent_id', required=True), uic=StringProperty('uic', required=True), unit_created_at=DateTimeProperty('unit_created_at', auto_now_add=True)>`
I have the following models to describe my database schema:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, backref
import sqlalchemy.dialects.mysql as mysql
Base = declarative_base()
class Country(Base):
__tablename__ = 'countries'
__table_args__ = {
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8'
}
id = Column(mysql.TINYINT(unsigned=True), primary_key=True)
name = Column(mysql.VARCHAR(30), nullable=False)
competitions = relationship('Competition', backref='country')
class Competition(Base):
__tablename__ = 'competitions'
__table_args__ = {
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8'
}
id = Column(mysql.INTEGER(unsigned=True), primary_key=True)
name = Column(mysql.VARCHAR(30), nullable=False)
country_id = Column(mysql.TINYINT(unsigned=True), ForeignKey('countries.id'))
teams = relationship('Team', backref("competition") )
class Team(Base):
__tablename__ = 'teams'
__table_args__ = {
'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8'
}
id = Column(mysql.INTEGER(unsigned=True), primary_key=True)
name = Column(mysql.VARCHAR(30), nullable=False)
competition_id = Column(mysql.INTEGER(unsigned=True), ForeignKey('competitions.id'), nullable=False)
and when I try to create a Team like:
team = Team()
I get the following traceback after the command above:
Traceback (most recent call last):
File "/home/giorgos/apps/Aptana_Studio_3/plugins/org.python.pydev_2.6.0.2012062121/pysrc/pydevd.py", line 1392, in <module>
debugger.run(setup['file'], None, None)
File "/home/giorgos/apps/Aptana_Studio_3/plugins/org.python.pydev_2.6.0.2012062121/pysrc/pydevd.py", line 1085, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "/home/giorgos/Documents/Aptana Studio 3 Workspace/BetPick/tests/insert_models.py", line 21, in <module>
team = Team()
File "<string>", line 2, in __init__
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 309, in _new_state_if_none
state = self._state_constructor(instance, self)
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 485, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 157, in _state_constructor
self.dispatch.first_init(self, self.class_)
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/event.py", line 291, in __call__
fn(*args, **kw)
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 2342, in _event_on_first_init
configure_mappers()
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 2258, in configure_mappers
mapper._post_configure_properties()
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 1167, in _post_configure_properties
prop.init()
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/interfaces.py", line 128, in init
self.do_init()
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/properties.py", line 911, in do_init
self._determine_joins()
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/properties.py", line 1034, in _determine_joins
self.secondary)
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/orm/properties.py", line 1028, in _search_for_join
a_subset=mapper.local_table)
File "/home/giorgos/.virtualenvs/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/util.py", line 262, in join_condition
b.foreign_keys,
AttributeError: 'tuple' object has no attribute 'foreign_keys'
what I am doing wrong ?
backref should be a keyword argument in your declaration of Competition.teams:
class Competition(Base):
# ...
teams = relationship('Team', backref="competition")
See the documentation on relationship. You can use a backref callable to configure the back reference explicitly, but you'd have to still use the backref keyword:
class Competition(Base):
# ...
teams = relationship('Team', backref=backref("competition", ... additional keywords ...))