1

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?

1
  • You could instantiate the db as a global variable (not sure if this is the right way to do it either, but it's how I tend to think of things) Commented Jun 5, 2015 at 5:12

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Great, it is something I was looking for, I completely forgot about class methods and attributes. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.