Very practical for ORM experimenting or in the command shell
see https://stackoverflow.com/questions/1297873/how-do-i-write-a-single-file-django-application
Run
python minimum.py
with Django on the environment
Very practical for ORM experimenting or in the command shell
see https://stackoverflow.com/questions/1297873/how-do-i-write-a-single-file-django-application
Run
python minimum.py
with Django on the environment
# This script is one of the smallest environments where Django models are | |
# fully functional. | |
# https://stackoverflow.com/questions/1297873/ | |
# how-do-i-write-a-single-file-django-application | |
import os | |
import sys | |
from datetime import datetime | |
import django | |
from django.apps import apps | |
from django.apps.config import AppConfig | |
from django.conf import settings | |
from django.db import connections, models, DEFAULT_DB_ALIAS | |
from django.db.models.base import ModelBase | |
NAME = 'test' | |
def main(): | |
class MyModel(models.Model): | |
applied_date = models.DateTimeField(null=True, blank=True) | |
modified_date = models.DateTimeField(null=True, blank=True) | |
@property | |
def applied(self): | |
if self.applied_date: | |
return self.applied_date > self.modified_date | |
return False | |
@applied.setter | |
def applied(self, value): | |
if value: | |
self.applied_date = datetime.now() | |
else: | |
self.modified_date = datetime.now() | |
self.save() | |
# SyncDB after model definition | |
syncdb(MyModel) | |
m = MyModel.objects.create(modified_date='2001-01-01') | |
m.applied = True | |
print MyModel.objects.count() | |
print MyModel.objects.all()[0].applied_date | |
assert MyModel.objects.all()[0].applied == True | |
def setup(): | |
with open(NAME + '.db', 'w'): | |
pass | |
settings.configure( | |
DEBUG=True, | |
DATABASES={ | |
DEFAULT_DB_ALIAS: { | |
'ENGINE': 'django.db.backends.sqlite3', | |
'NAME': NAME + '.db'}},) | |
app_config = AppConfig(NAME, sys.modules['__main__']) | |
apps.populate([app_config]) | |
django.setup() | |
original_new_func = ModelBase.__new__ | |
@staticmethod | |
def patched_new(cls, name, bases, attrs): | |
if 'Meta' not in attrs: | |
class Meta: | |
app_label = NAME | |
attrs['Meta'] = Meta | |
return original_new_func(cls, name, bases, attrs) | |
ModelBase.__new__ = patched_new | |
def syncdb(model): | |
connection = connections[DEFAULT_DB_ALIAS] | |
with connection.schema_editor() as editor: | |
editor.create_model(model) | |
def teardown(): | |
os.remove(NAME + '.db') | |
if __name__ == '__main__': | |
setup() | |
main() | |
teardown() |