How to dynamically create an existing non-abstract django model, abstract?

I think I have a more or less unorthodox and hacker question for you. I currently have a django project with several applications. I want to use non-abstract model (ModelA)one application ( app1) and use it in another application ( app2) by subclassing it. App1 models should not be transferred to the database, I just want to use the capabilities of the app1 and model classes, expanding its functionality and logic. I achieved this by adding both applications to settings.INSTALLED_APPSand preventing the migration of application1 models to the database.

INSTALLED_APPS += (
    'App1',
    'App2',
)

# This is needed to just use App1 models
# without creating it database tables
# See: http://stackoverflow.com/a/35921487/1230358
MIGRATION_MODULES = {
    'App1': None,
}

, , ... , app1 (ModelA), ModelA db app2_modelb. , App1 , app1_modela .

ModelA, (ModelB.Meta.abstract = True). , ModelA ModelB DB (app1_modelb).

, :

# In app1 -> models.py
class ModelA(models.Model):
    title = models.CharField(_('title'), max_length=255)
    subtitle =  models.CharField(_('subtitle'), max_length=255)

    class Meta:
        abstract = False # just explicitly for demonstration


# In app2 -> models.py
from app1.models import ModelA

class ModelB(ModelA):
    pass
    # Just extending ModelAdoes not create the fields title and subtitle fields in app2_modelb
    # because ModelA.meta.abstract = False

(-) :

# In app2 -> models.py
from app1.models import ModelA

def get_abstract_class(cls):
    o = dict(cls.__dict__)
    o['_meta'].abstract = True
    o['_meta'].app_label = 'app2'
    o['__module__'] = 'app2.models'

    #return type('Abstract{}'.format(cls.__name__), cls.__bases__, o)
    return type('Abstract{}'.format(cls.__name__), (cls,), o)

ModelB = get_abstract_class(ModelA)

class ModelC(ModelB):
    # title and subtitle are inherited from ModelA
    description = models.CharField(_('description'), max_length=255)

, () , - , ?

. fuzz , - app1. , app1 - django, pip.

+4
1

, app1

AbstractBaseModelA(models.Model):
    # other stuff here
    class Meta:
        is_abstract=True


ModelA(AbstractBaseModelA):
    # stuff

app2:

MobelB(AbstractBaseModelA):
    # stuff

, , , .

0

Source: https://habr.com/ru/post/1659591/


All Articles