Object-based default value in SQLAlchemy declarative

2024/10/13 22:22:23

With SQLAlchemy, it is possible to add a default value to every function. As I understand it, this may also be a callable (either without any arguments or with an optional ExecutionContext argument).

Now in a declarative scenario, I wonder if it is somehow possible to have a default function which is called with the object that is being stored. I.e. possibly like so:

Base = sqlalchemy.ext.declarative.declarative_base()
class BaseEntity(Base):value = Column('value', String(40), default=BaseEntity.gen_default)def gen_default(self):# do something with self, for example# generate a default value using some other data# attached to the objectreturn self.default_value

Is something like this possible? Or do I have to somehow set up an before-insertion hook for this (how?)?

Answer

before_insert is documented here:

http://docs.sqlalchemy.org/en/rel_0_7/orm/events.html#sqlalchemy.orm.events.MapperEvents.before_insert

examples here:

http://docs.sqlalchemy.org/en/rel_0_7/orm/events.html#mapper-events

i.e.

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import eventBase= declarative_base()class A(Base):__tablename__ = "a"id = Column(Integer, primary_key=True)data = Column(String)otherdata = Column(String)@event.listens_for(A, "before_insert")
def gen_default(mapper, connection, instance):instance.data = "Some default %s" % instance.otherdatae = create_engine("sqlite://")
Base.metadata.create_all(e)a = A(otherdata="some other data")
s = Session(e)
s.add(a)
s.commit()assert a.data == "Some default some other data"
https://en.xdnf.cn/q/69483.html

Related Q&A

High Resolution Image of a Graph using NetworkX and Matplotlib

I have a python code to generate a random graph of 300 nodes and 200 edges and display itimport networkx as nx import matplotlib.pyplot as pltG = nx.gnm_random_graph(300,200) graph_pos = nx.spring_layo…

how to read an outputted fortran binary NxNxN matrix into Python

I wrote out a matrix in Fortran as follows:real(kind=kind(0.0d0)), dimension(256,256,256) :: dense[...CALCULATION...]inquire(iolength=reclen)dense open(unit=8,file=fname,& form=unformatted,access=d…

python argparse subcommand with dependency and conflict

I want to use argparse to build a tool with subcommand. The possible syntax could be/tool.py download --from 1234 --interval 60 /tool.py download --build 1432 /tool.py clean --numbers 10So I want to us…

Running django project without django installation

I have developed a project with Django framework(python and mysql DB) in Linux OS(Ubuntu 12.04), I want to run this project in localhost in another machine with Linux(Ubuntu 12.04) without installing D…

redefine __and__ operator

Why I cant redefine the __and__ operator?class Cut(object):def __init__(self, cut):self.cut = cutdef __and__(self, other):return Cut("(" + self.cut + ") && (" + other.cut +…

How to find class of bound method during class construction in Python 3.1?

i want to write a decorator that enables methods of classes to become visible to other parties; the problem i am describing is, however, independent of that detail. the code will look roughly like this…

Multi-Threaded NLP with Spacy pipe

Im trying to apply Spacy NLP (Natural Language Processing) pipline to a big text file like Wikipedia Dump. Here is my code based on Spacys documentation example:from spacy.en import Englishinput = open…

Django Tastypie throws a maximum recursion depth exceeded when full=True on reverse relation.

I get a maximum recursion depth exceeded if a run the code below: from tastypie import fields, utils from tastypie.resources import ModelResource from core.models import Project, Clientclass ClientReso…

Adding a colorbar to two subplots with equal aspect ratios

Im trying to add a colorbar to a plot consisting of two subplots with equal aspect ratios, i.e. with set_aspect(equal):The code used to create this plot can be found in this IPython notebook.The image …

Why is C++ much faster than python with boost?

My goal is to write a small library for spectral finite elements in Python and to that purpose I tried extending python with a C++ library using Boost, with the hope that it would make my code faster. …