Python,flask和sqlalchemy新手在这里。我正在编写一个小应用程序来收集来自不同组(部门)的数据(来自excel文件)。每个部门都有关联的表,以及相关的字段。字段将具有预定义类型(数字,常规文本,日期)。我的models.py是:
from app import db
from sqlalchemy.schema import Sequence, CreateSequence
class FieldType(db.Model):
__tablename__ = 'fieldtype'
id = db.Column(db.Integer, db.Sequence('ftypeid'), primary_key = True)
name = db.Column(db.String(120))
python_type = db.Column(db.String(120))
python_import = db.Column(db.String(120))
class Field(db.Model):
__tablename__ = 'field'
id = db.Column(db.Integer, db.Sequence('fieldid'), primary_key = True)
name = db.Column(db.String(120), index = True, unique = True)
position = db.Column(db.Integer)
ftype = db.Column(db.FieldType) #The error is happening here.
tableinfoid = db.Column(db.Integer, db.ForeignKey('tableinfo.id'))
class TableInfo(db.Model):
__tablename__ = 'tableinfo'
id = db.Column(db.Integer, db.Sequence('tinfoid'), primary_key = True)
name = db.Column(db.String(30), index = True, unique = True)
fields = db.relationship('Field', backref='parent_table', lazy='dynamic')
class Department(db.Model):
__tablename__ = 'department'
id = db.Column(db.Integer, db.Sequence('dpartmntid'), primary_key = True)
name = db.Column(db.String(120), index = True, unique = True)
当我尝试运行该应用程序时,出现错误:
(env)[vagrant@localhost dataupload]$ ./run.py
Traceback (most recent call last):
File "./run.py", line 2, in <module>
from app import theapp
File "/home/vagrant/Development/dataupload/app/__init__.py", line 13, in <module>
from app import views, models
File "/home/vagrant/Development/dataupload/app/models.py", line 13, in <module>
class Field(db.Model):
File "/home/vagrant/Development/dataupload/app/models.py", line 20, in Field
ftype = db.Column(db.FieldType) #The error is happening here.
AttributeError: 'SQLAlchemy' object has no attribute 'FieldType'
我正在使用我对面向对象设计的理解。但我可能还不完全了解sqlalchemy如何进行映射 - 我紧跟Miguel的Flask Mega-Tutorial。但我想我会开始定义字段类型,然后从那里开始构建。如果我的理解存在差距,请帮我填写,以便完成这项任务。提前谢谢。
答案 0 :(得分:0)
因此,对于我所知道的任何数据库,您无法在SQL
中递归创建表。所以这一行
ftype = db.Column(db.FieldType)
鉴于此,没有任何意义。
Without more information I'm going to assume that you want a many to one relationship
Column('mtype_id', ForeignKey('FieldType.id'))
在这种情况下你真正想要的是什么。这允许您做的是在FieldType
的实例中使用该引用的键创建对Field
的特定实例的引用。