Revisions

gist: 217502 Download_button fork
public
Public Clone URL: git://gist.github.com/217502.git
Embed All Files: show embed
dynamic_model.py #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def create_model(name, fields=None, app_label='', module='', options=None, admin=None):
    """One example of how to create a model dynamically at run-time. The majority
of this is taken from code.djangoproject.com/wiki/DynamicModels"""
 
    class Meta:
        # Using type('Meta', ...) gives a dictproxy error during model creation
        pass
 
    if app_label:
        # app_label must be set using the Meta inner class
        setattr(Meta, 'app_label', app_label)
 
    # Update Meta with any options that were provided
    if options is not None:
        for key, value in options.items():
            setattr(Meta, key, value)
 
    # Set up a dictionary to simulate declarations within a class
    attrs = {'__module__': module, 'Meta': Meta}
 
    # Add in any fields that were provided
    if fields:
        attrs.update(fields)
 
    # Create an Admin inner class if admin options were provided
    if admin is not None:
        class Admin:
            pass
        for key, value in admin:
            setattr(Admin, key, value)
        attrs['Admin'] = Admin
 
    # Create the class, which automatically triggers ModelBase processing
    model = type(name, (models.Model,), attrs)
    
    # Line added for django => 1.0
    model.__name__ = ".".join([app_label, name])
 
    return model