Django ORM as a standalone library

Has there ever been an effort to decouple the ORM so it can work seamlessly with Flask/FastAPI? If not, why?

2 Likes

This works:

import os 
import django 

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
django.setup()

# And you're good... 

You can do settings.configure() if you don’t want to provide the settings module.

I hope that helps.

1 Like

Isn’t that importing the entire django library?
Are there any known caveats when using the ORM this way with Flask?

import django just imports the root django module. There’s very little in there.

TBH, I can’t see why you’d not just use Django if you’re using the ORM. Normally people say, “I don’t want to use the ORM so I won’t use Django”. But, no real issues, beyond missing out on all the good bits that Django gives you that go with the ORM without you having to do anything else. (The admin, forms, serialisers, and so on, not to mention third-party libraries…)

However, your question was, can you do it, to which yes you can. Have fun! :smile:

3 Likes

Cool thread here!

A use case of using just the ORM of Django doesn’t necessarily mean a web app, I have some services which I would love to be able to use the ORM (with migrations) of Django in.

2 Likes

I’ve got a couple of apps that don’t serve web pages at all. They exists only as a model layer and management commands. It’s useful having one framework servicing a number of different needs.

2 Likes

I found this repo. I have tried to use it. However it did not work properly. Maybe commits from experienced Django developers make this project more useful.

Hi @msenol86 — I don’t think an extra library is needed here. See the example I gave above:

It’s four lines to be able to you the ORM in a stand alone script. It’s not worth the maintenance cost of extra code on top of that I’d think. :thinking: