1

I have a SQLite 3 database and I need to write Python code that deals with it, basically the typical CRUD operations as an object oriented wrapper around the database. I find myself writing stupid SQL queries like SELECT this FROM there; and create a list of objects of a certain type.

The task feels so stupid and repetitive that I think someone must have written a code generator or something to do this more reliably than I ever could.

Such a generator or library shall be free of cost.

1 Answer 1

2

Peewee helped me reduce the code by ~50%.

And then I found that Peewee comes with a tool called Pwiz, which generates Python code from the database, which helped a lot, because that way I only need to be able to read the code and adapt it. I learn a lot while reading the generated code. That's great.

I ran the following code in a Pycharm terminal:

python -m pwiz -e sqlite my.db > my_db_model.py

Code generated (excerpt):

class Weeklytask(BaseModel):
    id = AutoField(column_name='ID', null=True)
    task_markdown = CharField(column_name='TaskMarkdown', null=True)
    year_of_study = IntegerField(column_name='YearOfStudy', null=True)

    class Meta:
        table_name = 'weeklytask'

When you use it, maybe it's good to know:

  • You can't write the query
    Assignments.select().where(Assignments.completed is None)
    but use
    Assignments.select().where(Assignments.completed.is_null(True))
    instead.
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.