我正在尝试创建一个提交有关Employee
的数据的嵌套表单。 Employee
有一个Photo
与之关联,一对一的关系。以下模型在没有__init__
函数的情况下工作,但是当我添加__init__
函数时,我得到InvalidRequest
异常。为什么__init__
的模型会失败?
sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|Employee|employee, expression 'Photo' failed to locate a name ("name 'Photo' is not defined"). If this is a class name, consider adding this relationship() to the <class 'blackduckflock.models.Employee'> class after both dependent classes have been defined.
class Employee(db.Model):
__tablename__ = 'employee'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200))
title = db.Column(db.String(200))
email = db.Column(db.String(200))
department = db.Column(db.String(200))
photo = db.relationship('Photo', uselist=False, back_populates='employee', cascade='all, delete')
def __init__(self, name='', title='', email='', department=''):
self.name = name
self.title = title
self.email = email
self.department = department
self.photo = photo
class Photo(db.Model):
__tablename__ = 'photo'
id = db.Column(db.Integer, primary_key=True)
image = db.Column(db.String(200))
storage_type_field = db.Column(db.String(255), default='')
bucket_name_field = db.Column(db.String(255), default='')
employee_id = db.Column(db.Integer, db.ForeignKey('employee.id'))
employee = db.relationship('Employee', back_populates='photo', cascade='all, delete')
def __init__(self, image='', storage_type_field='', bucket_name_field='', employee=Employee()):
self.image = image
self.storage_type_field = storage_type_field
self.bucket_name_field = bucket_name_field
self.employee = employee
答案 0 :(得分:1)
这是我的解决方案的答案:
class Photo(db.Model):
__tablename__ = 'photo'
id = db.Column(db.Integer, primary_key=True)
image = db.Column(db.String(200))
storage_type_field = db.Column(db.String(255), default='')
bucket_name_field = db.Column(db.String(255), default='')
employee_id = db.Column(db.Integer, db.ForeignKey('employee.id'))
employee = db.relationship('Employee', back_populates='photo')
def __init__(self, image='', storage_type_field='', bucket_name_field=''):
self.image = image
self.storage_type_field = storage_type_field
self.bucket_name_field = bucket_name_field
class Employee(db.Model):
__tablename__ = 'employee'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200))
title = db.Column(db.String(200))
email = db.Column(db.String(200))
department = db.Column(db.String(200))
photo = db.relationship('Photo', uselist=False, back_populates='employee', cascade='all, delete')
def __init__(self, name='', title='', email='', department='', photo=''):
self.name = name
self.title = title
self.email = email
self.department = department
self.photo = Photo()