最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

【已解决】Flask的SQLAlchemy出错:NoForeignKeysError Could not determine join condition between parent child tables on relationship

Flask crifan 886浏览 0评论

Flask中SQLAlchemy的代码:

    errandorAuthentication = db.relationship(‘AuthenticationErrandor’,
                                             uselist=False,
                                             back_populates=”user”,
                                             foreign_keys=”AuthenticationErrandor.id”)
class AuthenticationErrandor(db.Model):
    __tablename__ = ‘authenticationErrandors’
    id = db.Column(db.String(64), primary_key=True, default = generateAuthErrandorId, nullable=False)
    userId = db.Column(db.String(64), db.ForeignKey(“users.id”))
    user = db.relationship(“User”, back_populates=”errandorAuthentication”, foreign_keys=[userId])

运行出错:

Traceback (most recent call last):
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/gevent/pywsgi.py”, line 884, in handle_one_response
    self.run_application()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/geventwebsocket/handler.py”, line 88, in run_application
    return super(WebSocketHandler, self).run_application()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/gevent/pywsgi.py”, line 870, in run_application
    self.result = self.application(self.environ, self.start_response)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_sockets.py”, line 48, in __call__
    return self.wsgi_app(environ, start_response)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py”, line 271, in error_router
    return original_handler(e)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py”, line 268, in error_router
    return self.handle_error(e)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py”, line 271, in error_router
    return original_handler(e)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py”, line 268, in error_router
    return self.handle_error(e)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py”, line 477, in wrapper
    resp = resource(*args, **kwargs)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/views.py”, line 84, in view
    return self.dispatch_request(*args, **kwargs)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py”, line 587, in dispatch_request
    resp = meth(*args, **kwargs)
  File “/root/RunningFast/staging/runningfast/resources/Accesstoken.py”, line 226, in post
    foundUser = User.query.filter_by(phone=phone).first()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py”, line 498, in __get__
    mapper = orm.class_mapper(type)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/base.py”, line 421, in class_mapper
    mapper = _inspect_mapped_class(class_, configure=configure)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/base.py”, line 400, in _inspect_mapped_class
    mapper._configure_all()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py”, line 1222, in _configure_all
    configure_mappers()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py”, line 2840, in configure_mappers
    mapper._post_configure_properties()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py”, line 1765, in _post_configure_properties
    prop.init()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/interfaces.py”, line 183, in init
    self.do_init()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py”, line 1653, in do_init
    self._setup_join_conditions()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py”, line 1728, in _setup_join_conditions
    can_be_synced_fn=self._columns_are_mapped
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py”, line 1986, in __init__
    self._determine_joins()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py”, line 2090, in _determine_joins
    “specify a ‘primaryjoin’ expression.” % self.prop)
NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.errandorAuthentication – there are no foreign keys linking these tables.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a ‘primaryjoin’ expression.
{‘CONTENT_LENGTH’: ’65’,
‘CONTENT_TYPE’: ‘application/json’,
‘GATEWAY_INTERFACE’: ‘CGI/1.1’,
‘HTTP_ACCEPT’: ‘*/*’,
‘HTTP_ACCEPT_ENCODING’: ‘gzip, deflate’,
‘HTTP_ACCEPT_LANGUAGE’: ‘zh-CN,zh;q=0.8,en;q=0.6’,
‘HTTP_CACHE_CONTROL’: ‘no-cache’,
‘HTTP_CONNECTION’: ‘keep-alive’,
‘HTTP_HOST’: ‘115.29.173.126:21085’,
‘HTTP_ORIGIN’: ‘chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop’,
‘HTTP_POSTMAN_TOKEN’: ‘a01e4cd1-6f37-2e2a-68c6-117d087c4975’,
‘HTTP_USER_AGENT’: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36’,
‘PATH_INFO’: ‘/runningfast/api/v1.0/open/accesstoken’,
‘QUERY_STRING’: ”,
‘REMOTE_ADDR’: ‘58.209.164.112’,
‘REMOTE_PORT’: ‘64731’,
‘REQUEST_METHOD’: ‘POST’,
‘SCRIPT_NAME’: ”,
‘SERVER_NAME’: ‘AY140128113754462e2eZ’,
‘SERVER_PORT’: ‘21085’,
‘SERVER_PROTOCOL’: ‘HTTP/1.1’,
‘SERVER_SOFTWARE’: ‘gevent/1.1.2 gunicorn/19.6.0’,
‘werkzeug.request’: <Request ‘http://115.29.173.126:21085/runningfast/api/v1.0/open/accesstoken’ [POST]>,
‘wsgi.errors’: <gunicorn.http.wsgi.WSGIErrorsWrapper object at 0x7f01e62a5f50>,
‘wsgi.file_wrapper’: <class ‘gunicorn.http.wsgi.FileWrapper’>,
‘wsgi.input’: <gevent.pywsgi.Input object at 0x7f01e4abad50>,
‘wsgi.multiprocess’: False,
‘wsgi.multithread’: True,
‘wsgi.run_once’: False,
‘wsgi.url_scheme’: ‘http’,
‘wsgi.version’: (1, 0)} failed with NoForeignKeysError

改为:

    # errandorAuthentication = db.relationship(‘AuthenticationErrandor’,
    #                                          uselist=False,
    #                                          back_populates=”user”,
    #                                          foreign_keys=”AuthenticationErrandor.id”)
    errandorAuthenticationId = db.Column(db.String(64), db.ForeignKey(“authenticationErrandors.id”))
    errandorAuthentication = db.relationship(“AuthenticationErrandor”, back_populates=”user”, foreign_keys=[errandorAuthenticationId])
class AuthenticationErrandor(db.Model):
    __tablename__ = ‘authenticationErrandors’
    id = db.Column(db.String(64), primary_key=True, default = generateAuthErrandorId, nullable=False)
    userId = db.Column(db.String(64), db.ForeignKey(“users.id”))
    user = db.relationship(“User”, back_populates=”errandorAuthentication”, foreign_keys=[userId])

结果错误变成了:

Traceback (most recent call last):
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/gevent/pywsgi.py”, line 884, in handle_one_response
    self.run_application()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/geventwebsocket/handler.py”, line 88, in run_application
    return super(WebSocketHandler, self).run_application()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/gevent/pywsgi.py”, line 870, in run_application
    self.result = self.application(self.environ, self.start_response)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_sockets.py”, line 48, in __call__
    return self.wsgi_app(environ, start_response)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py”, line 271, in error_router
    return original_handler(e)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py”, line 268, in error_router
    return self.handle_error(e)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py”, line 271, in error_router
    return original_handler(e)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py”, line 268, in error_router
    return self.handle_error(e)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/app.py”, line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py”, line 477, in wrapper
    resp = resource(*args, **kwargs)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask/views.py”, line 84, in view
    return self.dispatch_request(*args, **kwargs)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_restful/__init__.py”, line 587, in dispatch_request
    resp = meth(*args, **kwargs)
  File “/root/RunningFast/staging/runningfast/resources/Accesstoken.py”, line 226, in post
    foundUser = User.query.filter_by(phone=phone).first()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py”, line 498, in __get__
    mapper = orm.class_mapper(type)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/base.py”, line 421, in class_mapper
    mapper = _inspect_mapped_class(class_, configure=configure)
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/base.py”, line 400, in _inspect_mapped_class
    mapper._configure_all()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py”, line 1222, in _configure_all
    configure_mappers()
  File “/root/Envs/RunningFast/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py”, line 2837, in configure_mappers
    raise e
InvalidRequestError: One or more mappers failed to initialize – can’t proceed with initialization of other mappers. Triggering mapper: ‘Mapper|AuthenticationErrandor|authenticationErrandors’. Original exception was: User.errandorAuthentication and back-reference AuthenticationErrandor.user are both of the same direction symbol(‘MANYTOONE’).  Did you mean to set remote_side on the many-to-one side ?
{‘CONTENT_LENGTH’: ’65’,
‘CONTENT_TYPE’: ‘application/json’,
‘GATEWAY_INTERFACE’: ‘CGI/1.1’,
‘HTTP_ACCEPT’: ‘*/*’,
‘HTTP_ACCEPT_ENCODING’: ‘gzip, deflate’,
‘HTTP_ACCEPT_LANGUAGE’: ‘zh-CN,zh;q=0.8,en;q=0.6’,
‘HTTP_CACHE_CONTROL’: ‘no-cache’,
‘HTTP_CONNECTION’: ‘keep-alive’,
‘HTTP_HOST’: ‘115.29.173.126:21085’,
‘HTTP_ORIGIN’: ‘chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop’,
‘HTTP_POSTMAN_TOKEN’: ‘6d60edda-d662-31d3-9917-1cad7f6b918a’,
‘HTTP_USER_AGENT’: ‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36’,
‘PATH_INFO’: ‘/runningfast/api/v1.0/open/accesstoken’,
‘QUERY_STRING’: ”,
‘REMOTE_ADDR’: ‘58.209.164.112’,
‘REMOTE_PORT’: ‘63172’,
‘REQUEST_METHOD’: ‘POST’,
‘SCRIPT_NAME’: ”,
‘SERVER_NAME’: ‘AY140128113754462e2eZ’,
‘SERVER_PORT’: ‘21085’,
‘SERVER_PROTOCOL’: ‘HTTP/1.1’,
‘SERVER_SOFTWARE’: ‘gevent/1.1.2 gunicorn/19.6.0’,
‘werkzeug.request’: <Request ‘http://115.29.173.126:21085/runningfast/api/v1.0/open/accesstoken’ [POST]>,
‘wsgi.errors’: <gunicorn.http.wsgi.WSGIErrorsWrapper object at 0x7f19bac0af50>,
‘wsgi.file_wrapper’: <class ‘gunicorn.http.wsgi.FileWrapper’>,
‘wsgi.input’: <gevent.pywsgi.Input object at 0x7f19b89c87a0>,
‘wsgi.multiprocess’: False,
‘wsgi.multithread’: True,
‘wsgi.run_once’: False,
‘wsgi.url_scheme’: ‘http’,
‘wsgi.version’: (1, 0)} failed with InvalidRequestError

再去改为:

class AuthenticationErrandor(db.Model):
    __tablename__ = ‘authenticationErrandors’
    id = db.Column(db.String(64), primary_key=True, default = generateAuthErrandorId, nullable=False)
    userId = db.Column(db.String(64), db.ForeignKey(“users.id”))
    # user = db.relationship(“User”, back_populates=”errandorAuthentication”, foreign_keys=[userId])

试试,结果:

InvalidRequestError: One or more mappers failed to initialize – can’t proceed with initialization of other mappers. Triggering mapper: ‘Mapper|User|users’. Original exception was: Mapper ‘Mapper|AuthenticationErrandor|authenticationErrandors’ has no property ‘user’

还是不行。

搜:

NoForeignKeysError: Could not determine join condition between parent/child tables on relationship

database – What is wrong with my relationships in SQL Alchemy? – Stack Overflow

InvalidRequestError: One or more mappers failed to initialize – can’t proceed with initialization of other mappers. Triggering mapper: ‘Mapper|User|users’. Original exception was: Mapper ‘Mapper|AuthenticationErrandor|authenticationErrandors’ has no property ‘user’

【总结】

最后用:

class User(db.Model):
    __tablename__ = ‘users’
    id = db.Column(db.String(64), primary_key=True, default = generateUserId, nullable=False)
    errandorAuthenticationId = db.Column(db.String(64), db.ForeignKey(“authenticationErrandors.id”))
    errandorAuthentication = db.relationship(‘AuthenticationErrandor’,
                                             uselist=False,
                                             # back_populates=”user”,
                                             foreign_keys=[errandorAuthenticationId])
class AuthenticationErrandor(db.Model):
    __tablename__ = ‘authenticationErrandors’
    id = db.Column(db.String(64), primary_key=True, default = generateAuthErrandorId, nullable=False)
    # userId = db.Column(db.String(64), db.ForeignKey(“users.id”))
    # user = db.relationship(“User”, back_populates=”errandorAuthentication”, foreign_keys=[userId])

就可以了。

转载请注明:在路上 » 【已解决】Flask的SQLAlchemy出错:NoForeignKeysError Could not determine join condition between parent child tables on relationship

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
58 queries in 0.095 seconds, using 18.97MB memory