[PYTHON] SQLAlchemy notes

Purpose of this entry

If you use SQLAlchemy occasionally, you will forget how to use it, so an entry to take notes every time you use it

Data acquisition

instance = sessoin.query(Model).filter_by(Schema=Value)
instance = sessoin.query(Model).filter(Model.Schema==Value) #Same as above

instance.one() #Returns an object when there is only one. If not(NoResultFound)Or if there are multiple(MultipleResultsFound)An error will occur.

instance.first() #If not, None is returned. If there is more than one, something one object is returned

instance.all() #List returns

[m.Schema for m for instance] #Like, instance is iterable.

instance.count() #The number is returned

Store data

model_data = Model(Schema=Value)
sessoin.add(model_data)
model_data.Schema2 = Value2
transaction.commit()
model_data = sessoin.query(Model).filter_by(Schema=Value).first()
if model_data is None:
	model_data = Model(Schema=Value)
sessoin.add(model_data)
model_data.Schema2 = Value2
transaction.commit()

Recommended Posts

SQLAlchemy notes
sqlalchemy
JetBrains_Learning Notes_003
pyenv notes
SQL notes
Pandas notes
Sphinx notes
django notes
Jupyter_Learning Notes_000
SQLAlchemy Pit
SQLAlchemy BaseModel
Django notes
pandas self-study notes
Python scraping notes
Mecab installation notes
Python study notes _000
concurrent.futures Usage notes
Theano installation notes
Jupyter study notes_006
[Django] as_view () notes
Notes about with
Python beginner notes
Theano's basic notes
Python study notes_006
Linux study notes
Notes on Flask
Django's order_by notes
Django Template notes
python C ++ notes
pyenv installation notes
Python study notes _005
Python grammar notes
Python Library notes
[SQLAlchemy] Read data
Hydrogen installation notes
Jupyter study notes_008
python personal notes
Jupyter study notes_004
Notes about pytorch
Jupyter study notes_001
python pandas notes
[Django] JWT notes
Python study notes_001
python learning notes
Python3.4 installation notes
Cabocha installation notes