Seite 1 von 1

[django] Mini test App zum spielen mit DB-Models...

Verfasst: Donnerstag 7. August 2008, 09:34
von jens
Ich hab früher schon einmal eine kleine Test App gemacht: http://www.python-forum.de/topic-10600.html
Diese hat aber die settings.py aus einem bestehenden django Projekt gebraucht.

Nun wollte ich mal ein paar Datenbank modelle testen und mit denen Spielen, ganz unabhängig von einer django App. Also hab ich mal ein wenig gebastelt. Dieses Skript kann man irgendwo hinwerfen und ausführen:

Code: Alles auswählen

#!/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 -"
Also im Bereich "Test model classes" erstellt man seine Modell Klassen. Ab dem Punk "Test code" kann man dann mit denen spielen.

Wichtig ist, das man bei den DB-Model Klassen die Angabe Meta.app_label = APP_LABEL einfügt und bei create_table() seine Klassen angibt, damit die Tabellen erzeugt werden.

Kennt jemand einen besseren/einfacheren Weg???

EDIT: Code update, crosspost: http://www.djangosnippets.org/snippets/1044/

Re: [django] Mini test App zum spielen mit DB-Models...

Verfasst: Donnerstag 10. Mai 2012, 09:14
von jens
Hab das Skript aktualisiert:

Code: Alles auswählen

#!/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/ (en)
    http://www.jensdiemer.de/permalink/150/mein-blog/355/mini-django-db-model-test-app/ (de)
    http://www.python-forum.de/viewtopic.php?f=3&t=15649 (de)

see also:
    https://github.com/readevalprint/mini-django/
    
Output from this current example code:
-------------------------------------------------------------------------------
 *** call 'syncdb':
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_testmodel
Creating table django_content_type
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
-------------------------------------------------------------------------------
new instance: TestModel entry: 'test'
instance data:
               id: None
     date_created: None
      last_update: None
             user: <User: test>
          content: 'test'
pk: 1
create date: 2012-05-10T05:14:06.820967
-------------------------------------------------------------------------------
- END -
-------------------------------------------------------------------------------    
"""

import os

BASE_PATH = os.path.abspath(os.path.dirname(__file__))
APP_LABEL = os.path.splitext(os.path.basename(__file__))[0]

os.environ["DJANGO_SETTINGS_MODULE"] = APP_LABEL

# settings:
DEBUG = TEMPLATE_DEBUG = True
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    APP_LABEL,
)
DATABASES = {
    'default': {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": ":memory:",
    }
}

if __name__ == "__main__":
    #______________________________________________________________________________
    # TestModel model classes:

    from django.db import models
    from django.contrib.auth.models import User

    class TestModel(models.Model):
        date_created = models.DateTimeField(auto_now_add=True)
        last_update = models.DateTimeField(auto_now=True)
        user = models.ForeignKey(User, blank=True, null=True)
        content = models.TextField()

        def __unicode__(self):
            return u"TestModel entry: '%s'" % self.content

        class Meta:
            app_label = "auth"  # Hack: Cannot use an app_label that is under South control, due to http://south.aeracode.org/ticket/520

    #------------------------------------------------------------------------------

    print " *** call 'syncdb':"
    from django.core import management
    management.call_command('syncdb', verbosity=1, interactive=False)
    print "-"*79

#    print "_"*79
#    print " *** diffsettings:"
#    management.call_command('diffsettings', verbosity=1, interactive=False)
#    print
#    print "-"*79

    #__________________________________________________________________________
    # play with TestModel:

    user = User(username="test")
    user.save()

    instance = TestModel(content="test", user=user)
    print "new instance:", instance
    print "instance data:"
    for field in instance._meta.fields:
        print "%17s: %s" % (field.name, repr(getattr(instance, field.name)))

    instance.save()
    print "pk:", instance.pk
    print "create date:", instance.date_created.isoformat()

    print "-"*79
    print "- END -"
EDIT: Nochmal aktualisiert.