SqlAlchemy non persistent column

2024/10/11 19:24:17

I am trying to define a model using sqlalchemy such that one of the columns i only need in memory for processing, i do not have a corresponding database column for that. I need it such that when i save the in memory object, it should not try to persist that special column.

More context: I am mapping a json object to an sql alchemy object using python marshmallow library. In the json response i have additional fields which i do not need in the database but do need in memory for computation.

I searched for the sqlalchemy docs, but could not find a way to skip the persistence of certain columns.

class AdSchema(Schema):"""Schema Mapping class."""id = fields.Int(dump_only=True)available_formats = fields.List(fields.Str())@post_loaddef make_ad(self, data):return AdModel(**data)class AdModel(Base):"""Ad ORM class."""__tablename__ = 'ad_model'id = Column(Integer, primary_key=True)

Am i missing something here?

What I am essentially looking for is a "virtual" attribute, similar to what is available in Rails ORM How to add a virtual attribute to a model in Ruby on Rails?

Answer

I was able to get around this by doing the following:

class MyModel(Base):__tablename__ = 'my_model'id = Column(Integer, primary_key=True)def __init__(self, **kwargs):self.non_persisted_column = kwargs['non_persisted_column']kwargs.pop('non_peristed_column')super().__init__(kwargs)

Effectively, a class attribute non_persisted_column is added to the class in the __init__ method. Then, non_persisted_column is removed from kwargs before kwargs is passed into the SQLAlchemy Base super class's __init__ method, so SQLAlchemy will not raise an error and will not persist non_persisted_column to the database.

https://en.xdnf.cn/q/69738.html

Related Q&A

Creating command line alias with python

I want to create command line aliases in one of my python scripts. Ive tried os.system(), subprocess.call() (with and without shell=True), and subprocess.Popen() but I had no luck with any of these me…

Remove unwanted lines in captcha text - opencv - python

I trying to get text from captcha image using opencv. Problem is text are masked with noise and it is complex to process with those horizontal line/noise.Original imageMy processed image :not sure how …

Double Summation in Python

I am trying to write a code to conduct a double summation (see pic) in which; M is the subjects, N is the Trials, Yijt is the measured wave form data (3d array)so far I have; Given Y is the data arra…

psycopg, double and single quotes insert

I ran into problems, while trying to insert to database:ur_psql.execute("""insert into smth(data, filedate, filedby)"""""" values(%s, NOW(), %s)""…

How to debug Python 2.7 code with VS Code?

For work I have to use Python 2.7. But when I use the "debug my python file" function in VS Code, I get an error. Even with a simple program, like : print()

Python Sequence of Numbers

Ive decided not to waste my summer and start learning python. I figured Id start learning looping techniques so I wanted to start with a basic list of numbers, aka, write a for loop that will generate…

Object initializer syntax (c#) in python?

I was wondering if there is a quick way to initialise an object in python. For example in c# you can instantiate an object and set the fields/properties like...SomeClass myObject = new SomeClass() { va…

Plotly.io doesnt see the psutil package even though its installed

Im trying to execute the following code:import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib %matplotlib inline import seaborn as snsimport plotly.graph_objects as g…

How to get MultiCells in Pyfpdf Side by side?

I am making a table of about 10 cells with headings in them. They will not fit accross the page unless I use multi_cell option. However I cant figure out How to get a multi_cell side by side. When I ma…

Django: Require Checkbox to be ticked to Submit Form

Im creating a form in Django (using ModelForm). There are many checkboxes, and I want to make it so that one of these must be selected in order to submit the form. I dont mean any one checkbox, but on…