Login

create_model_instances management command

Author:
Lacrymology
Posted:
January 21, 2013
Language:
Python
Version:
1.4
Tags:
model instance object-creation config-file
Score:
0 (after 0 ratings)

This management command is run like this: ./manage.py -a someapp filename.cfg

it looks in someapp's directory for a file called /config/filename.cfg with the format explained in the help text, and creates the model instances described in the config file.

It uses the configobj module.

this would be an example config file:

[project.Profile]
[[fields]]
receive_notifications = False
[[children]]
[[[auth.User]]]
[[[[fields]]]]
username = AnnonymousUser
password = ! # set unusable password. There's no way yet to hash and set a given password
email = none@example.com
 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from optparse import make_option
import os
from django.core.management import BaseCommand
import configobj
from django.db.models import get_app, get_model

class Command(BaseCommand):
    """
    Creates django models from config files
    """
    help = """[-a appname ]<config filename>

Create models based on a config file.
The format is:
[<applabel>.<model>]
[[fields]]
field1 = value
field2 = value
[[children]]
[[[<applabel>.<model>]]]
fk_field = <fieldname>
[[[[fields]]]]
field1 = value
field2 = value
"""
    option_list = BaseCommand.option_list + (
        make_option('-a', '--app',
                    action='store',
                    dest='app',
                    default = '<default app label>',
                    help='application to get the config file from'),
        )

    def get_config(self, app_label, config_filename):
        if not config_filename.endswith('.cfg'):
            config_filename += '.cfg'
        app_module = get_app(app_label)
        if hasattr(app_module, '__path__'):
            app_path = app_module.__path__
        else:
            app_path = app_module.__file__
        filename = os.path.join(os.path.dirname(app_path),
                                'config',
                                config_filename)
        return configobj.ConfigObj(filename)

    def create_object(self, model, cfg, parent=None):
        app_label, modelname = model.split('.')
        ModelClass = get_model(app_label, modelname)
        kwargs = {}
        if parent is not None:
            kwargs[cfg['fk_field']] = parent
        kwargs.update(cfg['fields'])
        obj, new = ModelClass.objects.get_or_create(**kwargs)
        if not new:
            self.stdout.write('%s object with fields %s already exists: id %d' % (
                model, str(cfg['fields']), obj.pk))
        return obj

    def handle(self, *args, **options):
        if not args:
            print "The config file is required"
            return
        config = self.get_config(options['app'], args[0])
        for model, cfg in config.items():
            obj = self.create_object(model, cfg)
            for childmodel, ccfg in cfg['children'].items():
                child = self.create_object(childmodel, ccfg, parent=obj)

More like this

  1. extras.py for management commands by dnordberg 7 years, 11 months ago
  2. backupdb command by msaelices 7 years, 1 month ago
  3. JSON serializer supporting natural primary keys by bdauvergne 1 year, 4 months ago
  4. MySQL django password function by mcosta 6 years, 2 months ago
  5. Access Control Mechanisms with mod_wsgi by johnnoone 5 years, 5 months ago

Comments

Please login first before commenting.