0

I have made a class called Database that I use to manage a connection to a Postgres database via psycopg3. This enables me to do things like:

db = Database(postgres_connection_data)
class_one_instance.insert(insert_data, db)
class_two_instance.insert(insert_data, db)
db.commit()

The exception handling in the insert methods is such that we only get to db.commit() if both inserts have worked, which is exactly what I want.

I am exploring Django as an option in our stack and I would like to replace the implementation of class two's insert() with save() from models.Model. How can I use my Database object with save()?

def insert(self, insert_data, db):
    self.save()
  • Don't try to implement your own database backend for Django, it will be either a ton of work, of you will loose many of the magic functions of Django. Instead adapt the behavior to your needs. There are many options to modify the transaction handling. To get a more details answer you will have to ask a more detailed question. – Klaus D. Sep 01 '23 at 10:44
  • The problem is that we are not in a position to make all the inserts Django inserts yet. The long term goal would be to have them all Django inserts and deprecate the Database class, but we are not in a position to do that yet. – concrete_boi Sep 01 '23 at 10:51
  • [save()](https://docs.djangoproject.com/en/4.2/ref/models/instances/#saving-objects) is a method of `models.Model` so you have to be working with an instance of `models.Model` to use it. – Adrian Klaver Sep 01 '23 at 15:24

1 Answers1

0

First, I don't think you need to follow this logic. Bear in mind that Django features a set of ORM-based features that help you simplify this challenge.

Normally, you would configure the connection to the database in the setting.py file and the code would be:

classe_one_instance = models.Classe_One(insert_data)
classe_one_instance.save()

I don't know if I understood the intention of the algorithm well, but it would be functional to do it that way

Magno Dev
  • 1
  • 1