shrimpdrake
shrimpdrake

Reputation: 1576

generate django 2.0 model from a dict

Consider the following Django model:

class Person(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)

I would like to define this class from a “static” dict (to be specific in my case it is generated from a file which will not change - so no need to makemigrations and migrate apart from first time).

Here is some pseudo-code to better explain what I want to achieve:

persondict = {‘first_name‘: models.CharField(max_length=255), ‘last_name’: models.CharField(max_length=255)}

class Person(models.Model):
    #generate fields from persondict    

Upvotes: 1

Views: 98

Answers (1)

Bob
Bob

Reputation: 6173

This is just to start with. Note that you have to change the app_label inside the function, also this will work if you define it inside your models.py where you will use it, otherwise you will need to replace the '__module__' with the appropriate value.

def generate_person_model_from_a_dict(person_model_dict):

    class Meta:
        app_label = 'your_app_label_here'

    person_model_dict.update({
        'Meta': Meta,
        '__module__': generate_person_model_from_a_dict.__module__,
    })

    Person = type("Person", (models.Model,), person_model_dict)
    return Person

Meta.app_label is needed here to let the Django know which app the newly constructed model should be attached to, e.g. if you are creating it for the app blog and set the model's app_label to blog, then the Django will know, that the app has this model on it (just like you would define it in your blog/models.py)

__module__ is a special attribute of python objects (you can read details about it here https://docs.python.org/3/reference/datamodel.html ) To be brief, it lets Django to know which module your class belongs to, it uses it mostly to display various messages to it's user, see here: https://github.com/django/django/search?utf8=%E2%9C%93&q=module&type= (just set it to your models.py like in the above example is therefore what Django pretty much expects)

Upvotes: 1

Related Questions