In one celery task I need to create temporary table in database. In this article Daniel Roseman explained how to create one. But this solution does not work in Django 1.9. I tried to look into Django docs and Google but I was unable to find anything useful.
Code from mentioned article which worked in Django 1.8:
from django.db import models, cursor
from django.contrib.contenttypes.management import update_contenttypes
from django.core.management import call_command
class TempCustomerAddress(models.Model):
address = models.ForeignKey('accounts.Address')
legacy_id = models.CharField(max_length=12, unique=True)
class Meta:
app_label = 'utils'
class Command(NoArgsCommand):
def handle_noargs(self, **options):
models.register_models('utils', TempCustomerAddress)
models.signals.post_syncdb.disconnect(update_contenttypes)
call_command('syncdb')
# ... do importing and stuff referring to TempCustomerAddress ...
cursor = connection.cursor()
cursor.execute('DROP TABLE `utils_tempcustomeraddress`')
In django 1.9 you actually don't need to register anything. You just create model the same way as in
models.py
and that's it. You only need to make sure that it is not inmodels.py
file because than it will be permanent model. This example assumes that you already ran all migrations.I needed to create a temporary model derived from a "permanent" model, and use temporary table storage to avoid polluting the tables of the permanent one. After a lot of poking around including an article relating to Django 0.96, some newer material it points to for Django 1.2 and some old material based on migration tech integrated into Django I finally came up with a recipe that works with Django 2.0.
First, I needed to explicitly specify the database table name using the Meta:
Then I created the Model class by copying what I needed from the original:
The hard part was tracking down how to create the new table for the model. Once found, the answer was simple: