Preliminary study of PeeWee, because SQLAlchemy is really too heavyweight, document is too disgusting, PeeWee easy to get started much easier, also very light
The first time you use DB is initialized with Initdb, unless you delete the SQLite database, you only need to call SaveData and Agequery
PeeWee Study:
In PeeWee, a class that inherits the model class is defined as a table in a database
Feild in a class, as a column (field) of a database
A model class instance is a row
Example
From PeeWee Import *
db = Sqlitedatabase (' people.db ')
Class Person (Model):
Name = Charfield ()
Birthday = Datefield ()
Is_relative = Booleanfield ()
Class Meta:
Database = db # This model uses the "people.db" database.
Class Pet (Model):
Owner = Foreignkeyfield (person, related_name= ' pets ')
Name = Charfield ()
Animal_type = Charfield ()
Class Meta:
Database = db # This model uses the "PEOPLE.DB" database
Db.connect ()
Db.create_tables ([Person, Pet])
Save data:
>>> from datetime import Date
>>> Uncle_bob = person (name= ' Bob ', Birthday=date (1960, 1, +), is_relative=true)
>>> Uncle_bob.save () # Bob is now stored in the database
1
>>> Bob_kitty = pet.create (owner=uncle_bob, name= ' Kitty ', animal_type= ' cat ')
>>> Herb_fido = pet.create (Owner=herb, name= ' Fido ', animal_type= ' dog ')
>>> Herb_mittens = pet.create (Owner=herb, name= ' mittens ', animal_type= ' cat ')
>>> Herb_mittens_jr = pet.create (Owner=herb, Name= ' Mittens Jr ', animal_type= ' cat ')
Delete data:
>>> herb_mittens.delete_instance () # He had a great life
1
Querying data (accessing data for related fields based on the feild of the Class):
>>> grandma = Person.select (). WHERE (Person.name = = ' Grandma L. '). Get ()
>>> grandma = person.get (Person.name = = ' Grandma L. ')
List all records:
>>> for WHO in Person.select ():
... print Person.name, person.is_relative
...
Bob True
Grandma L. True
Herb False
Compare the differences between the two types of queries:
>>> query = Pet.select (). WHERE (Pet.animal_type = = ' Cat ')
>>> for pet in query:
... print Pet.name, Pet.owner.name
...
Kitty Bob
Mittens Jr Herb
>>> query = (Pet
... . Select (Pet, person)
... . Join (person)
... . WHERE (Pet.animal_type = = ' Cat '))
>>> for pet in query:
... print Pet.name, Pet.owner.name
...
Kitty Bob
Mittens Jr Herb
The latter is more efficient and the latter does not make unnecessary inquiries