Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What model should a SQLalchemy database column be to contain an array of data?

So I am trying to set up a database, the rows of which will be modified frequently. Every hour, for instance, I want to add a number to a particular part of my database. So if self.checkmarks is entered into the database equal to 3, what is the best way to update this part of the database with an added number to make self.checkmarks now equal 3, 2? I tried establishing the column as db.Array but got an attribute error:

AttributeError: 'SQLAlchemy' object has no attribute 'Array'

I have found how to update a database, but I do not know the best way to update by adding to a list rather than replacing. My approach was as follows, but I don't think append will work because the column cannot be an array:

ven = data.query.filter_by(venid=ven['id']).first()
ven.totalcheckins = ven.totalcheckins.append(ven['stats']['checkinsCount'])
db.session.commit()

Many thanks in advance

like image 787
zch Avatar asked Nov 25 '12 06:11

zch


People also ask

What are SQLAlchemy models?

SQLAlchemy (source code) is a Python library for accessing persistent data stored in relational databases either through raw SQL or an object-relational mapper.

What does Create_all do in SQLAlchemy?

Sqlalchemy create_all method is used to create a new table into the database. This method will first check whether the table exists in the database or not if suppose it has found an existing table it will not create any table.

What is Backref in SQLAlchemy?

The sqlalchemy backref is one of the type keywords and it passed as the separate argument parameters which has to be used in the ORM mapping objects. It mainly includes the event listener on the configuration attributes with both directions of the user datas through explicitly handling the database relationships.


1 Answers

If you really want to have a python list as a Column in SQLAlchemy you will want to have a look at the PickleType:

array = db.Column(db.PickleType(mutable=True))

Please note that you will have to use the mutable=True parameter to be able to edit the column. SQLAlchemy will detect changes automatically and they will be saved as soon as you commit them.

If you want the pickle to be human-readable you can combine it with json or other converters that suffice your purposes.

like image 106
Alexander Jung-Loddenkemper Avatar answered Sep 23 '22 19:09

Alexander Jung-Loddenkemper