[PYTHON] How to check ORM behavior in one file with django

How to check ORM behavior in one file with django

I wrote How to make hello world with one file before. The thing you want to try most with django may be the ORM part. How to try the ORM part with only one file.

It takes a bit of work to try it out in one file, but with django these days it's fairly easy to do.

Specifically, the following work is required.

--Set settings from python side --Register model in django's Application Registry --Generate a table for each model

Set settings from python side

If there is no settings, the following exception will occur.

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

As per the error message, either register DJANGO_SETTINGS_MODULE as an environment variable or callsettings.configure (). The minimum required settings are as follows.

from django.conf import settings

settings.configure(
    DEBUG=True,
    DATABASES={"default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": ":memory:"
    }},
    INSTALLED_APPS=[__name__]
)

DEBUG = True is necessary when outputting the query result of sql, so it is better to add it. In addition, DB settings are required. Here, the on-memory DB of sqlite is specified. For ʻINSTALLED_APPS, if you forget to specify it when registering the model described later, the relationship of ManyToMany` will not work properly.

Register model in django's Application Registry

Call django.setup (). This will call populate () in django.apps.registry.Apps. In this, the model will be registered in the registry of django. If this is not done, the following error will occur at the timing when Model.save () is called.

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

Also, as a caveat, set ʻapp_label` to the model to be defined. Without this, the model class cannot be generated. I get the following error.

IndexError: list index out of range

When defining it, do as follows.

class X(models.Model):
    name = models.CharField(max_length=255, default="foo", blank=True)

    class Meta:
        app_label = __name__

Generate a table for each model

Normally, you will generate a DB table with python manage.py migrate etc. There is no procedure for one file. You need to think about other ways. For example, let's create a function that creates a table.

from django.db import connections
from django.core.management.color import no_style


def create_table(model):
    connection = connections['default']
    cursor = connection.cursor()
    sql, references = connection.creation.sql_create_model(model, no_style())
    for statement in sql:
        cursor.execute(statement)

    for f in model._meta.many_to_many:
        create_table(f.rel.through)


#It is necessary to generate one by one
create_table(X)

Summary

The above can be summarized as follows. With this, you can easily check the behavior of the model.

# -*- coding:utf-8 -*-
import django
from django.db import models
from django.conf import settings
from django.db import connections
from django.core.management.color import no_style


settings.configure(
    DEBUG=True,
    DATABASES={"default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": ":memory:"
    }},
    INSTALLED_APPS=[__name__]
)


def create_table(model):
    connection = connections['default']
    cursor = connection.cursor()
    sql, references = connection.creation.sql_create_model(model, no_style())
    for statement in sql:
        cursor.execute(statement)

    for f in model._meta.many_to_many:
        create_table(f.rel.through)


class X(models.Model):
    name = models.CharField(max_length=255, default="foo", blank=True)

    class Meta:
        app_label = __name__


if __name__ == "__main__":
    import logging
    logging.basicConfig(level=logging.DEBUG)
    django.setup()
    create_table(X)

    xs = X.objects.bulk_create([X(id=1), X(id=2), X(id=3)])

    print(X.objects.count())

Recommended Posts

How to check ORM behavior in one file with django
How to do zero-padding in one line with OpenCV
How to get people to try out django rest framework features in one file
How to drop Google Docs in one folder in a .txt file with python
How to use Laravel-like ORM / query builder Orator in Django
[Django] How to give input values in advance with ModelForm
How to convert 0.5 to 1056964608 in one shot
How to reflect CSS in Django
How to get started with Django
How to authenticate with Django Part 2
How to authenticate with Django Part 3
[Django] How to read variables / constants defined in an external file
How to display legend marks in one with Python 2D plot
How to calculate "xx time" in one shot with Python timedelta
How to do arithmetic with Django template
How to delete expired sessions in Django
How to work with BigQuery in Python
How to check opencv version in python
How to do Server-Sent Events in Django
How to convert DateTimeField format in Django
How to deal with garbled characters in json of Django REST Framework
How to deal with memory leaks in matplotlib.pyplot
How to read a CSV file with Python 2/3
[REAPER] How to play with Reascript in Python
How to implement Rails helper-like functionality in Django
Save multiple models in one form with Django
How to develop a cart app with Django
How to create a JSON file in Python
[Python] How to read excel file with pandas
How to reflect ImageField in Django + Docker (pillow)
How to run some script regularly in Django
How to deal with run-time errors in subprocess.call
How to implement "named_scope" of RubyOnRails with Django
How to check / extract files in RPM package
How to use tkinter with python in pyenv
How to create a Rest Api in Django
How to read a file in a different directory
Sample to put Python Kivy in one file
File upload with django
How to convert / restore a string with [] in python
How to get multiple model objects randomly in Django
How to do hash calculation with salt in Python
How to define Decorator and Decomaker in one function
Explain in detail how to make sounds with python
How to deal with pyenv initialization failure in fish 3.1.0
How to run tests in bulk with Python unittest
How to load files in Google Drive with Google Colaboratory
How to measure mp3 file playback time with python
How to access with cache when reading_json in pandas
How to use bootstrap in Django generic class view
How to convert JSON file to CSV file with Python Pandas
How to use template engine in pyramid 1 file application
How to upload files in Django generic class view
[Work efficiency] How to change file names in Python
How to use Decorator in Django and how to make it
How to reference static files in a Django project
How to deal with Executing transaction: failed in Anaconda
How to use fixture in Django to populate sample data associated with a user model
How to start the code written in Atom with one command without starting teminal
How to check in Python if one of the elements of a list is in another list
How to write custom validations in the Django REST Framework