middleofdreams
middleofdreams

Reputation: 353

Python, DB and models

I am writing some python gui app (PySide to be exact) and I am using my own class to handling DB. What's the correct way to use models? Currently I have something like this:

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

And it's working just fine... But I have a feeling that something is wrong here... I mean, I have to pass DB to each model, I don't think that's correct way. How to do it in proper way without using frameworks like SQLAlchemy and so on?

Upvotes: 1

Views: 804

Answers (1)

bakkal
bakkal

Reputation: 55448

You can at least create a base class, let's called it Model (like in Django, or Base as it is called in SQLAlchemy)

We'll keep a reference to the db object as a class attribute so it is the same for all instances, and inherited so you don't have to pass it around

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()

I hope you see the idea and adapt it to your needs!

Upvotes: 2

Related Questions