Django-MySQL

4.19.0 · active · verified Sat Apr 11

Django-MySQL extends Django's built-in MySQL and MariaDB support to leverage their specific features not available on other databases. It provides custom fields (like JSONField, ListField), aggregates, lookups, and system checks. The library is actively maintained with releases often aligned with new Django major versions, ensuring compatibility and continued feature development.

Warnings

Install

Imports

Quickstart

To quickly get started with Django-MySQL, first ensure you have a MySQL/MariaDB database configured in your Django settings. Add 'django_mysql' to your `INSTALLED_APPS`. This example demonstrates defining a model with a `django_mysql.models.JSONField` which provides native JSON support for MySQL. After defining your models, run `makemigrations` and `migrate` to apply the database schema changes. Note: For a runnable example, ensure your `settings.py` includes `INSTALLED_APPS` and `DATABASES` configurations, and substitute 'myapp' with the actual name of your Django app containing the model.

import os
from django.conf import settings
from django.apps import apps

if not apps.ready:
    settings.configure(
        INSTALLED_APPS=[
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django_mysql',
            'myapp' # Assuming your models are in 'myapp'
        ],
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': 'mydatabase',
                'USER': os.environ.get('MYSQL_USER', 'root'),
                'PASSWORD': os.environ.get('MYSQL_PASSWORD', ''),
                'HOST': os.environ.get('MYSQL_HOST', 'localhost'),
                'PORT': os.environ.get('MYSQL_PORT', '3306'),
                'OPTIONS': {
                    'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
                }
            }
        },
        DEFAULT_AUTO_FIELD='django.db.models.BigAutoField',
        TIME_ZONE='UTC',
        USE_TZ=True,
    )
    apps.populate(settings.INSTALLED_APPS)

from django.db import models
from django_mysql.models import JSONField

# Define a simple Django model using Django-MySQL's JSONField
class MyModel(models.Model):
    name = models.CharField(max_length=100)
    data = JSONField(default=dict)

    def __str__(self):
        return self.name

# This code snippet would typically be followed by:
# python manage.py makemigrations myapp
# python manage.py migrate
# And then interactive usage:
# from myapp.models import MyModel
# instance = MyModel.objects.create(name='Sample Item', data={'version': 1, 'items': ['a', 'b']})
# print(f"Created: {instance.name} with data {instance.data}")
# instance.data['status'] = 'processed'
# instance.save()
# print(f"Updated: {instance.name} with data {instance.data}")

print("Django-MySQL model definition with JSONField is ready.")

view raw JSON →