Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy non persistent column

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_load
  def 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?

like image 347
Pratik Khadloya Avatar asked Feb 28 '18 18:02

Pratik Khadloya


People also ask

What is _sa_instance_state in SQLAlchemy?

_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance.

What is column in SQLAlchemy?

function sqlalchemy.orm. column_property(*columns, **kwargs) Provide a column-level property for use with a mapping. Column-based properties can normally be applied to the mapper's properties dictionary using the Column element directly.

How do I get column names in SQLAlchemy?

To access the column names we can use the method keys() on the result. It returns a list of column names. Since, we queried only three columns, we can view the same columns on the output as well.

What is identity map in SQLAlchemy?

identity map. A mapping between Python objects and their database identities. The identity map is a collection that's associated with an ORM Session object, and maintains a single instance of every database object keyed to its identity.


1 Answers

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.

like image 59
jones-chris Avatar answered Nov 15 '22 08:11

jones-chris