Skip to content Skip to sidebar Skip to footer

Will Using The Django Orm In A Python Library Cause Trouble?

I've enjoyed using Django quite a bit over the years. Right now I'm working for a company that is building some shared internal libraries for accessing information from our databas

Solution 1:

OK, here's my own attempt to answer the question after some research.

I can create a baseclass for my models anywhere in the library as follows:

from django.db import models
from django.apps import apps
import django.conf

django.conf_settings.configure(
    DATABASES = ...
)

apps.populate((__name__,))

classLibModel(models.Model):
    classMeta:
        abstract = True
        app_label = __name__

Then anywhere in the library I can create my own models with this baseclass. Since I'm not relying on the "app" for the database names, I need to state them explicitly.

classSpecificModel(LibModel):
    # fields go here
    class Meta(LibModel.Meta):
        db_table ="specific_model_table_name"

This gets around my concern of having to simulate the structure of an "app". The name property in the base class supplies Django with all it needs, and then Django quits whining about not finding an app. The other model files can live wherever they want.

However, there is still a big concern I have which might be lethal. Django's initialization itself is still singleton in nature. If my library were itself imported by a Django application, it would all crash and burn. I've asked for solutions to this in this follow up question.

Post a Comment for "Will Using The Django Orm In A Python Library Cause Trouble?"