简体   繁体   English

Flask-SQLAlchemy一对多关系无法找到名称

[英]Flask-SQLAlchemy One to Many relationship failed to locate a name

I have a Flask app with Flask-SQLAlchemy. 我有一个带有Flask-SQLAlchemy的Flask应用程序。 I'm trying to make a one to many relationship from a user to a trip. 我正在尝试从用户到旅行建立一对多的关系。 I saw that, if I use the declarative_base of SQLAlchemy it works but when I use the db.Model from Flask-SQLAlchemy it dosen't work. 我看到了,如果我使用SQLAlchemy的declarative_base可以正常工作,但是当我使用Flask-SQLAlchemy的db.Model时却无法正常工作。

I'm getting the following error: 我收到以下错误:

sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|User|User, expression 'Trip' failed to locate a name ("name 'Trip' is not defined"). If this is a class name, consider adding this relationship() to the <class 'models.user.User'> class after both dependent classes have been defined.

Here are the models: 这些是模型:

database.py database.py

from flask import abort 
from flask_sqlalchemy import SQLAlchemy 
from sqlalchemy import exc

db = SQLAlchemy()


class Mixin(db.Model):
    __abstract__ = True
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime, default=db.func.now())
    date_changed = db.Column(
        db.DateTime, nullable=True, onupdate=db.func.now())
    date_to = db.Column(db.DateTime, nullable=True)

user.py user.py

from database import Mixin, db

class User(Mixin, db.Model):
    __tablename__ = 'User'        
    trips = db.relationship(
        'Trip',
        backref=db.backref('user', lazy='joined'),
        lazy='dynamic'
    )     

trip.py Trip.py

from database import Mixin, db

class Trip(Mixin, db.Model):
    __tablename__ = 'Trip'
    title = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(250), nullable=False)        
    user_id = db.Column(
        db.Integer,
        db.ForeignKey('User.id'),
        nullable=False
    )       

Storing all models in one file is a good idea, but only for a small number of models. 将所有模型存储在一个文件中是一个好主意,但仅适用于少数模型。 For the large I would prefer to store models in semantically separate files. 对于大型应用程序,我希望将模型存储在语义上独立的文件中。

models
├── __init__.py
├── model1.py
├── model2.py
└── model3.py

In the __init__.py need to import all models files __init__.py需要导入所有模型文件

import models.model1.py
import models.model2.py
import models.model3.py

I fixed it by using one file for my models. 我通过为模型使用一个文件来修复它。 I didn't have enough models to need multiple model files anyway. 无论如何,我没有足够的模型来需要多个模型文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM