Skip to content

Instantly share code, notes, and snippets.

@kyanny
Created January 25, 2021 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyanny/5415d6013c0479dc20de9a9a9bd0cd13 to your computer and use it in GitHub Desktop.
Save kyanny/5415d6013c0479dc20de9a9a9bd0cd13 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# https://docs.djangoproject.com/en/3.1/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage
import django
from django.conf import settings
# https://blog.amedama.jp/entry/sqlite3-in-memory-issue
import tempfile
tfile = tempfile.NamedTemporaryFile()
import sqlite3
conn = sqlite3.connect(tfile.name)
c = conn.cursor()
c.execute('CREATE TABLE book (id integer primary key, title text not null)')
c.execute('CREATE TABLE book_log (id integer primary key, book_id int not null, title text not null)')
settings.configure(DEBUG=True, DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': tfile.name,
}
})
django.setup()
# Now this script or any imported module can use any part of Django it needs.
from django.db import models
class Book(models.Model):
id = models.BigAutoField(primary_key=True)
title = models.TextField(null=False)
def __str__(self):
return self.title
class Meta:
app_label = 'standalone'
db_table = 'book'
class BookLog(models.Model):
id = models.BigAutoField(primary_key=True)
book_id = models.BigIntegerField(null=False)
title = models.TextField(null=False)
def __str__(self):
return self.title
class Meta:
app_label = 'standalone'
db_table = 'book_log'
# https://docs.djangoproject.com/ja/3.1/topics/signals/
from django.db.models.signals import pre_save
from django.dispatch import receiver
@receiver(pre_save, sender=Book)
def my_handler(sender, instance, **kwargs):
# `instance` is a model object to be updated
old_book = Book.objects.filter(id=instance.id).first()
if not old_book:
return
if old_book.title == instance.title:
return
BookLog(book_id=old_book.id, title=old_book.title).save()
book = Book(title="My First Book")
book.save()
print(book)
print(BookLog.objects.count())
book.save()
print(book)
print(BookLog.objects.count())
book.title = "My 1st Book"
book.save()
print(book)
print(BookLog.objects.count())
print(BookLog.objects.all())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment