【问题标题】:Sqlalchemy print the output object of a querySqlalchemy 打印查询的输出对象
【发布时间】:2021-10-15 03:30:05
【问题描述】:

我一直在寻找,但找不到任何东西......

我的模型是,

class Departament(db.Model):

    id = Column(Integer, primary_key=True)
    departament = Column(String, unique=True)
    depmv = relationship('Mvpordep', backref='line', lazy='select')
    depfac = relationship('Bill', backref='line_fac', lazy='select')

    def __init__(self, departament):

        self.departament = departament

    def __repr__(self):
        return '{}'.format(self.departament) 

你试试

departament = Departament.query.filter_by(departament='ti').first()

print(departament.id)

但它给了我以下错误

AttributeError: 'NoneType' object has no attribute 'id'

当我获得多行并使用 for 循环对其进行迭代时,没问题。但是如果我尝试用 for 循环来做,合乎逻辑的事情就会发生

for out in departament:
    print(out.id)
TypeError: 'NoneType' object is not iterable

我不明白会发生什么

【问题讨论】:

  • 将此行从 'Departament.query.filter_by(departament='ti').first()' 更改为 'Departament.objects.filter_by(departament='ti').first()'
  • 运气不好AttributeError: type object 'Departament' has no attribute 'objects'
  • 您的实际型号名称是Departmento 不仅是Department 最后还有一个“o”
  • 是的,你是对的,对不起。写帖子的时候出错了。非常感谢您的提示。最后我已经找到了问题所在。这是因为开发数据库和生产数据库不同,并且开发中不存在数据。非常感谢您的帮助!

标签: python flask sqlalchemy orm flask-sqlalchemy


【解决方案1】:

您正在部门类中使用__repr__() 函数。因此,如果您从部门类中获取数据,您将只能获取部门的数据(如您创建的那样)。

这里的错误是,您获取的数据中没有 id,它是唯一的部门。这就是为什么你会收到Nonetype 错误。

如果您想要部门类中的所有数据,请从部门类中删除 __repr__() 函数(和 __init__())或在 __repr__() 函数(和 __init__())中声明每个列名。

【讨论】:

    猜你喜欢
    • 2011-08-03
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 2020-11-03
    • 2023-03-29
    相关资源
    最近更新 更多