如何在 sqlalchemy 声明中设置属性默认值?

编程入门 行业动态 更新时间:2024-10-28 06:27:37
本文介绍了如何在 sqlalchemy 声明中设置属性默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 SQLAlchemy Declarative 中,如何为列设置默认值,以便瞬态或挂起的对象实例将具有这些默认值?一个简短的例子:

In SQLAlchemy Declarative, how do I set up default values for columns, such that transient or pending object instances will have those default values? A short example:

from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class A(Base): __tablename__ = "A" id = Column(Integer, primary_key=True) word = Column(String, default="adefault") a = A() print a.word

天真地,我希望它的输出是adefault.当然,输出实际上是None.即使在添加到会话时,它也会保持None 并且仅在我提交(或刷新)会话并从数据库中重新读取实例值时才会被填充.

Naively, I would expect the output from this to be adefault. Of course, the output is actually None. Even when adding to a session, it staysNone and only gets filled when I commit (or flush) the session, and re-read the instance value from the database.

有没有办法在不将实例刷新到数据库的情况下设置属性默认值?我尝试调查 ColumnDefault 文档,似乎没有明显的方法来检查类型/python 值,以便在自定义声明性基类中手动设置它.

Is there any way to set an attribute default without flushing the instance to the database? I tried investigating the ColumnDefault documentation, and there doesn't seem to be an obvious way to inspect the type/python value, so as to manually set it in a custom declarative baseclass.

推荐答案

向类添加构造函数并在那里设置默认值.从数据库加载行时,构造函数不会运行,因此可以执行此操作.

Add a constructor to your class and set the default value there. The constructor doesn't run when the rows are loaded from the database so it is fine to do this.

class A(Base): __tablename__ = "A" id = Column(Integer, primary_key=True) word = Column(String) def __init__(self): self.word = "adefault" a = A() print a.word

__init__ 的示例映射"rel="noreferrer">SA 文档.

There are examples of using __init__ in similar ways in the SA Docs.

更多推荐

如何在 sqlalchemy 声明中设置属性默认值?

本文发布于:2023-10-26 22:15:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531500.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:默认值   属性   声明   如何在   sqlalchemy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!