Python、数据库和模型

Python, DB and models

我正在编写一些 python gui 应用程序(确切地说是 PySide)并且我正在使用我自己的 class 来处理数据库。使用模型的正确方法是什么?目前我有这样的东西:

class DB(object):
    def __init__(self, dbfile):
         some db connect work

    def updateEntry(entryid):
         some update query etc

    def getEntry(entryid):
         fetching entry from db

    def createEntry(entryvalue):
         insert entry


class EntryModel(object):
    def __init__(db,entryid=None,entryvalue=None):
        self.db=db
        self.entryid=entryid
        self.entryvalue=entryvalue

        if entryid is None:
            self.db.createEntry(self.entryvalue)
        elif self.entryvalue is None:
            self.db.getEntry(self.entryid)

   def some_func(self):
        some other work

它工作得很好......但我觉得这里有问题......我的意思是,我必须将 DB 传递给每个模型,我认为这是不正确的方法。如何在不使用 SQLAlchemy 等框架的情况下以正确的方式做到这一点?

您至少可以创建一个基础 class,我们称它为 Model(就像在 Django 中一样,或者在 SQLAlchemy 中称为 Base

我们将保留对 db 对象的引用作为 class 属性,因此它对所有实例都是相同的,并且是继承的,因此您不必传递它

class Model(object):
    db = None # This var is a class attribute

    @classmethod
    def init_db(cls):
        cls.db = your_code_to_create_db()

class Entry(Model):
    def __init__(self, entry_id, entry_value):
        self.entry_id = entry_id
        self.entry_value = entry_value
        super(Entry, self).__init__()

    def save(self):
        # Use db here
        self.db

# To use
Model.init_db() # Inits the one db var for the class
entry = Entry(...)
entry.save()

希望您能看到这个想法并根据您的需要进行调整!