python实现简单的ORM

2018-02-27 11:18:09来源:oschina作者:NLGBZJ人点击

分享

写简单的小项目这些挺方便的


from peewee import * from datetime import date #http://docs.peewee-orm.com/en/latest/peewee/quickstart.html db = SqliteDatabase('people.db') class BaseModel(Model): class Meta: database = db # This model uses the "people.db" database.


class Person(BaseModel): name = CharField() birthday = DateField() is_relative = BooleanField()


class Pet(Model): owner = ForeignKeyField(Person, backref='pets') name = CharField() animal_type = CharField()


class Meta: database = db # this model uses the "people.db" database """ grandma = Person.get(Person.name == 'Grandma L.') for person in Person.select(): print(person.name, person.is_relative) query = Pet.select().where(Pet.animal_type == 'cat') for pet in query: print(pet.name, pet.owner.name)


for pet in Pet.select().where(Pet.owner == uncle_bob).order_by(Pet.name): print(pet.name)


""" if __name__=='__main__': print 'd' if 0: db.connect() db.create_tables([Person, Pet])uncle_bob = Person(name='Bob', birthday=date(1960, 1, 15), is_relative=True) uncle_bob.save() # bob is now stored in the database db.close() else: print Person.get(Person.name == 'Bob') for person in Person.select():print(person.name, person.is_relative) # Returns: 1

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台