Dictionary of tags in declarative SQLAlchemy?

2024/4/14 5:22:00

I am working on a quite large code base that has been implemented using sqlalchemy.ext.declarative, and I need to add a dict-like property to one of the classes. What I need is the same as in this question, but in a declarative fashion. Can anyone with more knowledge in SQLAlchemy give me an example? Thanks in advance...

Answer

Declarative is just another way of defining things. Virtually you end up with the exact same environment than if you used separated mapping.

Since I answered the other question, I'll try this one as well. Hope it gives more upvotes ;)

Well, first we define the classes

from sqlalchemy import Column, Integer, String, Table, create_engine
from sqlalchemy import orm, MetaData, Column, ForeignKey
from sqlalchemy.orm import relation, mapper, sessionmaker
from sqlalchemy.orm.collections import column_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_baseengine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base(bind=engine)class Note(Base):__tablename__ = 'notes'id_item = Column(Integer, ForeignKey('items.id'), primary_key=True)name = Column(String(20), primary_key=True)value = Column(String(100))def __init__(self, name, value):self.name = nameself.value = value        class Item(Base):__tablename__ = 'items'id = Column(Integer, primary_key=True)name = Column(String(20))description = Column(String(100))_notesdict = relation(Note, collection_class=column_mapped_collection(Note.name))notes = association_proxy('_notesdict', 'value', creator=Note)def __init__(self, name, description=''):self.name = nameself.description = descriptionBase.metadata.create_all()

Now let's make a test:

Session = sessionmaker(bind=engine)
s = Session()i = Item('ball', 'A round full ball')
i.notes['color'] = 'orange'
i.notes['size'] = 'big'
i.notes['data'] = 'none's.add(i)
s.commit()
print i.notes

I get:

{u'color': u'orange', u'data': u'none', u'size': u'big'}

Now let's check the notes table...

for note in s.query(Note):print note.id_item, note.name, note.value

I get:

1 color orange
1 data none
1 size big

It works!! :D

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

Related Q&A

How to connect to a GObject signal in python, without it keeping a reference to the connecter?

The problem is basically this, in pythons gobject and gtk bindings. Assume we have a class that binds to a signal when constructed:class ClipboardMonitor (object):def __init__(self):clip = gtk.clipboar…

openpyxl please do not assume text as a number when importing

There are numerous questions about how to stop Excel from interpreting text as a number, or how to output number formats with openpyxl, but I havent seen any solutions to this problem:I have an Excel s…

NLTK CoreNLPDependencyParser: Failed to establish connection

Im trying to use the Stanford Parser through NLTK, following the example here.I follow the first two lines of the example (with the necessary import)from nltk.parse.corenlp import CoreNLPDependencyPars…

How to convert hex string to color image in python?

im new in programming so i have some question about converting string to color image.i have one data , it consists of Hex String, like a fff2f3..... i want to convert this file to png like this.i can c…

How to add values to a new column in pandas dataframe?

I want to create a new named column in a Pandas dataframe, insert first value into it, and then add another values to the same column:Something like:import pandasdf = pandas.DataFrame() df[New column].…

value error happens when using GridSearchCV

I am using GridSearchCV to do classification and my codes are:parameter_grid_SVM = {dual:[True,False],loss:["squared_hinge","hinge"],penalty:["l1","l2"] } clf = …

How to remove english text from arabic string in python?

I have an Arabic string with English text and punctuations. I need to filter Arabic text and I tried removing punctuations and English words using sting. However, I lost the spacing between Arabic word…

python module pandas has no attribute plotting

I am a beginner of Python. I follow the machine learning course of Intel. And I encounter some troubles in coding. I run the code below in Jupyter and it raises an AttributeError.import pandas as pd st…

pandass resample with fill_method: Need to know data from which row was copied?

I am trying to use resample method to fill the gaps in timeseries data. But I also want to know which row was used to fill the missed data.This is my input series.In [28]: data Out[28]: Date 2002-09-0…

Inefficient multiprocessing of numpy-based calculations

Im trying to parallelize some calculations that use numpy with the help of Pythons multiprocessing module. Consider this simplified example:import time import numpyfrom multiprocessing import Pooldef t…