python - SQLAlchemy/PostgreSQL mutable, deduplicated array -


after having read article on implementing tags postgresql, i've decide work postgresql's array datatype.

but understand, there not built-in support mutable arrays in sqlalchemy. prevent duplicates within these arrays (there isn't built-in 'set-like' datatype in postgresql).

i'm having hard time finding concrete examples of how use , manipulate sqlalchemy arrays (declaratively) backed postgresql, simple append/update operations. how set array , append (if to-be-appended string isn't duplicate) sqlalchemy array datatype?

i ran problem. solution used create type inherits sqlalchemy.ext.mutable.mutable , set, wrap in type backed sqlalchemy.dialects.postgresql.array.

from sqlalchemy.ext.mutable import mutable sqlalchemy.dialects.postgresql import array  modmethods = ['add', 'clear', 'difference_update', 'discard',                'intersection_update', 'pop', 'remove',               'symmetric_difference_update', 'update',               '__ior__', '__iand__', '__isub__', '__ixor__']  class mutableset(mutable, set):     @classmethod     def coerce(cls, key, value):         if not isinstance(value, cls):             return cls(value)         else:             return value  def _make_mm(mmname):     def mm(self, *args, **kwargs):         try:             retval = getattr(set, mmname)(self, *args, **kwargs)         finally:             self.changed()         return retval     return mm  m in modmethods:     setattr(mutableset, m, _make_mm(m))  del modmethods, _make_mm  def arrayset(_type, dimensions=1):     return mutableset.as_mutable(array(_type, dimensions=dimensions)) 

this overrides methods of set can change set's value adding call mutable's changed method, causing sqlalchemy flush possibly changed value database.

then, declare type in sqlalchemy type inside it; instance, declare set of integers:

column(arrayset(integer)) 

then, when using it, can treat value standard python set, operators , methods unchanged.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -