0

I have been surfing the web for 3-5 days looking for a proper answer to this solution. I see lots of code for Flask but none for Django to answer my question. Perhaps this is because Django has a built-in ORM, and if it would be considered odd to use SqlAlchemy with Django, I'd like to be made aware of that. It would be a high ranking answer for me personally.

The question is: what is the best way (or even one way) to set up Django with sqlAlchemy?

I want to:

  • House the initialization of the database in one file if and only if that is what you do in sqlAlchemy to avoid bugs.
  • Keep my database models only in one file, exporting them and then importing into the file(s) where I need them.
  • I do not want to use Aldjemy as seen here. I'm doing this to learn Django

An example ideal file structure, this is how i think it should look:

..mysite
....someAppName
......db
......-db.py
......-models.py
....__init__.py
....admin.py
....apps.py
....models.py <-- maybe models should go here, but where to export the db connection from?
....tests.py
....urls.py
....views.py

Currently in db/db.py I have:

from sqlalchemy import Table, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import event

import sqlalchemy as db

engine = db.create_engine('sqlite:///census.sqlite')
connection = engine.connect()

Base = declarative_base()

class Viewer(Base):
    __tablename__ = 'viewer'
    id = Column(Integer, primary_key=True)


class Session(Base):
    __tablename__ = "session"
    session_id = Column(Integer, primary_key=True),
    user_id = Column(ForeignKey("user_account.user_id")),
    ip = Column(String(30)),
    height = Column(Integer)
    width = Column(Integer)

and I want this code to export properly into other files so I can use it there without duplicating code.

For instance in views.py I'd like to be able to do:

@csrf_exempt
def create_user(request):
    # Create a user to hold sessions.
    user_id = randint(0, 100000)
    print(user_table)
    stmt = insert(user_table).values(user_id=user_id)
    with engine.connect() as conn:
        userData.create_all(engine)  # can take this out after I export db correctly
        result = conn.execute(stmt)
        conn.commit()
    return HttpResponse("user created! {}".format(result.inserted_primary_key))

But the version that uses the declarative_base() models.

Hope that was clear, thanks to all who read or help.

P.S. I realize asking for a "best way" may be a bit subjective, ideally the answer here provides a guideline for future users of Django + sqlAlchemy.

plutownium
  • 69
  • 1
  • 6

0 Answers0