-2

I've a Python project with ~30 SQLAlchemy models and I'm not sure where they belong. All models belong to the DB but also to a module, so I'm not sure about the right namespace.

Here are some ideas:

  1. import db.models.MyModelA
  2. import my.module.MyModelA
  3. import my.module.db.MyModelA

Is there any best practice that I didn't find yet? I think this is a software design/architecture issue and not necessarily limited to Python.

Any advice is appreciated. Thanks.

1
  • Which approach best meets your project's specific non-functional requirements? Feb 5, 2021 at 14:49

2 Answers 2

2

Actually, your question has hundreds of correct answers. because it's completely related to your application scope and design. Let's review the definition of "Best Solution" in this case. The structure of your files needs to be organized enough to avoid confusion, conflicts, and misuse and they Must Be meaningful, useful, maintainable, and reusable.

So make the situation clear for yourself. Do you have any other Classes like DTOs that need to be placed into the model's directory or not? if put different groups of files with different usage and structure in the same directory, they should be clearly separated by some naming conventions like prefix/suffixes.

Solution #1

Models
--UserDB.py // what you are going to use for your ORM
--UserDTO.py // what you are going to return in the response of your API.

Solution #2

Models
-- DB
---- User.py
-- DTO
---- User.py

In this solution, you might encounter a situation that you need to import one of them somewhere, and then you can import one of them wrongly or if you need both of them, you need to use an alias for them and it makes confusion for the other developers.

Solution #3

Models
-- DB
---- UserDB.py
-- DTO
---- UserDTO.py
0

this is interesting. I have had my models in one single file but given my application needs to be expanded now from 4 models to 10, i figured i introduce a directory, "orm" and store all my models inside them.

    orm
├── plans.py
├── address.py
├── customer.py
└── reward_redemption.py

I'm using SQLalchemy 2.0 and given the models have relationships (ie. 1 to many, many to many), I keep getting errors to do with circular references or complaints that one of the models has been partially declared.

If anyone has any good tutorials for how to set up SQLalchemy 2.0+ with models separated into separate python files, please do share.

thank you :)

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.