Django: How to add fields to a model from another module

0

I have worked with an ERP (Open Object) in which modules that affect module models are added, which allow us to add functions and fields. In django something similar is possible through Meta.proxy but this limits the possibility of creating new fields. Checking the structure only allows you to create virtual fields, which I imagine are not included in the database.

My idea is to emulate the behavior of this framework (Open Object) allowing to add optional modules that add logic and fields to existing models. This will allow me to keep my modules relatively isolated allowing me to uninstall them without having unnecessary fields in the model they affect.

    
asked by Saúl Galán 30.11.2017 в 23:30
source

1 answer

0

Your question is somewhat broad, but depending on what you need, I can recommend two options to you from the beginning, which in my opinion could help you

The first one is to work with abstract classes, that give you a basic structure with which you can create classes that inherit from these

miapp1 / models.py

    class ModeloBase(models.Model):
        name = models.CharField(max_length=100)
        apellido = models.CharField(max_length=100)

        class Meta:
            abstract = True

miapp2 / models.py

    from miapp1.models import *

    class Persona(ModeloBase):
        campo1 = models.CharField(max_length=100)
        campo2 = models.CharField(max_length=100)

        class Meta:
            db_table = "app2_persona"

The above will create the app2_personnel table in the database with the columns specified in ModelBase and in Person

The second option is to create the models (without the parent being abstract) and inherit them, with the difference that two tables will be created in the database, one for the parent model and another for the child model, when storing the records, the values corresponding to the parent model, will go to the table of the parent model, and in the table of the child model the fields corresponding to this will be stored and you will have a field that links to the record stored in the parent model.

miapp1 / models.py

    class ModeloBase(models.Model):
        name = models.CharField(max_length=100)
        apellido = models.CharField(max_length=100)

miapp2 / models.py

    from miapp1.models import *

    class Persona(ModeloBase):
        campo1 = models.CharField(max_length=100)
        campo2 = models.CharField(max_length=100)

And in the same way you create objects from person and you can access the attributes of the parent model, from this object

    persona = Persona()
    persona.name = "Mi nombre"
    persona.save()
    
answered by 04.12.2017 в 15:59