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
69
70
71
72
73
74
75
76
77
78
79 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Standalone django model test with a 'memory-only-django-installation'.
You can play with a django model without a complete django app installation.
http://www.djangosnippets.org/snippets/1044/
"""
import os
APP_LABEL = os.path.splitext(os.path.basename(__file__))[0]
os.environ["DJANGO_SETTINGS_MODULE"] = "django.conf.global_settings"
from django.conf import global_settings
global_settings.INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
APP_LABEL,
)
global_settings.DATABASE_ENGINE = "sqlite3"
global_settings.DATABASE_NAME = ":memory:"
from django.core.management import sql
from django.db import models, connection
from django.core.management.color import no_style
STYLE = no_style()
def create_table(*models):
""" Create all tables for the given models """
cursor = connection.cursor()
def execute(statements):
for statement in statements:
cursor.execute(statement)
for model in models:
execute(connection.creation.sql_create_model(model, STYLE)[0])
execute(connection.creation.sql_indexes_for_model(model, STYLE))
execute(sql.custom_sql_for_model(model, STYLE))
execute(connection.creation.sql_for_many_to_many(model, STYLE))
#______________________________________________________________________________
# Your test model classes:
from django.db import models
class Test(models.Model):
my_id = models.CharField(max_length=32, primary_key = True)
text = models.TextField()
def __unicode__(self):
return u"Test entry: '%s'" % self.text
class Meta:
app_label = APP_LABEL
#------------------------------------------------------------------------------
if __name__ == "__main__":
print "- create the model tables...",
from django.core import management
management.call_command('syncdb', verbosity=1, interactive=False)
print "OK"
# Here you must insert, all existing test models:
create_table(Test)
#__________________________________________________________________________
# Your test code:
instance = Test(text="test")
print instance
for field in instance._meta.fields:
print field, field.name
print instance._meta.pk
print "- END -"
|
Comments