我有一个用户模型,我正试图初始化,我不断得到
AttributeError:“NoneType”对象没有属性“set”
经过进一步检查,我了解到sqlalchemy将其模型转换为映射器,映射器中包含使其成为工具属性的属性InstrumentedAttribute很明显,是的这一切都发生在初始化对象时。你知道吗
这只发生在usermodel上,其他什么都没有。你知道吗
我尝试使用app\u上下文来查看是否是由于db不在范围内。但没用。你知道吗
class userData(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(128), nullable=False)
# TODO need to add hashing for the password
password = db.Column(db.String(10), nullable=False)
type = db.Column(db.String(5), nullable=False)
facility_id = db.Column(db.Integer, db.ForeignKey('facility.id'), nullable=True)
auth_hash = db.Column(db.String, nullable=True)
def __init__(self, *args, **kwargs) -> None:
super(userData, self).__init__(*args, **kwargs)
def __getattr__(self, item):
if item is 'facility':
facility = facilityData.query.filter(facilityData.id == self.facility_id).first()
if facility is None:
return "No Facility Found"
else:
return facility.facility_name
作为参考,这个很好用:
class barcodeData(db.Model):
__tablename__ = 'barcodes'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
barcode = db.Column(db.String(128), nullable=False)
medid = db.Column(db.String(128), nullable=False)
user = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
def __init__(self, data):
'''class constructor'''
self.barcode = data.get('barcode')
self.medid = data.get('medid')
self.user = data.get('user')
这是我在尝试创建新的userData对象时遇到的错误。你知道吗
import models
import app
with app.app.app_context():
models.userData(name='admin2', password='test2', facility_id=1)
我甚至尝试过另一种方法,不使用app\u context(),然后专门从模型导入用户数据。还尝试在每次迭代中交替使用app\u上下文。你知道吗
attributes.py in __set__(self, instance, value)
258
259 def __set__(self, instance, value):
--> 260 self.impl.set(
261 instance_state(instance), instance_dict(instance), value, None
262 )
AttributeError: 'NoneType' object has no attribute 'set'
所以我才意识到为什么会发生这种行为。基本上,它与db scope或诸如此类的东西无关。你知道吗
这个问题是因为在实例化类的过程中,类的属性变成了可查询的属性,这意味着sqlalchemy需要引用这些属性。它是通过使用
__getattr__
顺序推断类型来实现的(分贝柱)在创建对象之前。你知道吗因为我重写了
__getattr__
,希望能更容易地将序列化转换为json,所以它使用默认返回的值,即None。这就是导致错误的原因。你知道吗相关问题 更多 >
编程相关推荐