Skip to content

About

TiDB dialect for Django

Topics

Resources

Stars

36 stars

Watchers

29 watching

Forks

Repository files navigation

TiDB dialect for Django

PyPI PyPI - Python Version PyPI - Downloads .github/workflows/ci.yml

This adds compatibility for TiDB to Django.

Installation Guide

Prerequisites

Before installing django-tidb, ensure you have a MySQL driver installed. You can choose either mysqlclient(recommended) or pymysql(at your own risk).

Install mysqlclient (Recommended)

Please refer to the mysqlclient official guide

Install pymysql (At your own risk)

django-tidb has not been tested with pymysql

pip install pymysql

Then add the following code at the beginning of your Django's settings.py:

import pymysql

pymysql.install_as_MySQLdb()

Installing django-tidb

To install django-tidb, you need to select the version that corresponds with your Django version. Please refer to the table below for guidance:

The patch release number of Django doesn't correspond to the patch release number of django-tidb. For example, django-tidb 6.0.x works with every Django 6.0.x. Use the latest patch release of each.

django django-tidb install command
v6.0.x v6.0.x pip install 'django-tidb~=6.0.0'
v5.2.x v5.2.x pip install 'django-tidb~=5.2.0'
v5.1.x v5.1.x pip install 'django-tidb~=5.1.0'
v5.0.x v5.0.x pip install 'django-tidb~=5.0.0'
v4.2.x v4.2.x pip install 'django-tidb~=4.2.0'
v4.1.x v4.1.x pip install 'django-tidb~=4.1.0'
v3.2.x v3.2.x pip install 'django-tidb~=3.2.0'

Usage

Set 'ENGINE': 'django_tidb' in your settings to this:

import os

DATABASES = {
    'default': {
        'ENGINE': 'django_tidb',
        'NAME': 'django',
        'USER': os.environ['TIDB_USER'],
        'PASSWORD': os.environ['TIDB_PASSWORD'],
        'HOST': os.environ['TIDB_HOST'],
        'PORT': 4000,
    },
}
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Note

Connect with a dedicated database user that has only the privileges your application needs, not root. Keep the password out of settings.py, for example in an environment variable as shown above.

Connecting over TLS

Use TLS when the connection to TiDB leaves the local host. TiDB Cloud Starter and Essential require TLS for public endpoint connections. With mysqlclient, set ssl_mode and the CA certificate in OPTIONS:

DATABASES = {
    'default': {
        'ENGINE': 'django_tidb',
        ...
        'OPTIONS': {
            'ssl_mode': 'VERIFY_IDENTITY',
            'ssl': {'ca': '/etc/ssl/certs/ca-certificates.crt'},
        },
    },
}

VERIFY_IDENTITY encrypts the connection and also checks that the server certificate is valid for the host name. The CA certificate path depends on your OS (for example /etc/ssl/cert.pem on macOS).

For TiDB Cloud Dedicated, download the cluster's CA certificate from the TiDB Cloud console and set it as ca instead of the system CA bundle.

For details, see TLS Connections to TiDB Cloud Starter or Essential and TLS Connections to TiDB Cloud Dedicated.

Using AUTO_RANDOM

AUTO_RANDOM is a feature in TiDB that generates unique IDs for a table automatically. It is similar to AUTO_INCREMENT, but it can avoid write hotspot in a single storage node caused by TiDB assigning consecutive IDs. It also has some restrictions, please refer to the documentation.

To use AUTO_RANDOM in Django, you can do it in either of the following two ways:

  1. Declare globally in settings.py as shown below, it will affect all models:

    DEFAULT_AUTO_FIELD = 'django_tidb.fields.BigAutoRandomField'
  2. Manually declare it in the model as shown below:

    from django_tidb.fields import BigAutoRandomField
    
    class MyModel(models.Model):
        id = BigAutoRandomField(primary_key=True)
        title = models.CharField(max_length=200)

BigAutoRandomField is a subclass of BigAutoField, it can only be used for primary key and its behavior can be controlled by setting the parameters shard_bits and range. For detailed information, please refer to the documentation.

Migrate from AUTO_INCREMENT to AUTO_RANDOM:

  1. Check if the original column is BigAutoField(bigint), if not, migrate it to BigAutoField(bigint) first.

  2. In the database configuration (settings.py), define SET @@tidb_allow_remove_auto_inc = ON in the init_command. You can remove it after completing the migration.

    # settings.py
    DATABASES = {
        'default': {
            'ENGINE': 'django_tidb',
            ...
            'OPTIONS': {
                'init_command': 'SET @@tidb_allow_remove_auto_inc = ON',
            }
    
        }
    }
  3. Finally, migrate it to BigAutoRandomField(bigint).

Note

AUTO_RANDOM is supported after TiDB v3.1.0, and only support define with range after v6.3.0, so range will be ignored if TiDB version is lower than v6.3.0

Using AUTO_ID_CACHE

AUTO_ID_CACHE allows users to set the cache size for allocating auto-increment IDs. TiDB guarantees that AUTO_INCREMENT values are monotonic (always increasing) on a per-server basis, but the value may appear to jump dramatically if an INSERT is performed against another TiDB server, because each server has its own cache, whose size is controlled by AUTO_ID_CACHE. TiDB v6.4.0 introduced a centralized auto-increment ID allocating service: setting AUTO_ID_CACHE to 1 when creating a table enables MySQL compatibility mode without losing performance.

To use AUTO_ID_CACHE in Django, you can specify tidb_auto_id_cache in the model's Meta class as shown below when creating a new table:

class MyModel(models.Model):
    title = models.CharField(max_length=200)

    class Meta:
        tidb_auto_id_cache = 1

But there are some limitations:

  • tidb_auto_id_cache can only affect the table creation, after that it will be ignored even if you change it.
  • tidb_auto_id_cache only affects the AUTO_INCREMENT column.

Vector (Beta)

TiDB supports the vector data type on TiDB Cloud, and on TiDB Self-Managed from v8.4.0 (experimental). See Vector Search Overview.

VectorField is still in beta, and the API may change in the future.

To use VectorField in Django, you need to install django-tidb with vector extra:

pip install 'django-tidb[vector]'

Then you can use VectorField in your model:

from django.db import models
from django_tidb.fields.vector import VectorField

class Test(models.Model):
    embedding = VectorField(dimensions=3)

You can also add an HNSW vector index when creating the table. For more information, see Vector Search Index. A vector index is built on TiFlash, so the cluster needs a TiFlash node. django-tidb sets a TiFlash replica for the table (ALTER TABLE ... SET TIFLASH REPLICA 1) before it creates the index.

from django_tidb.fields.vector import L2Distance, VectorField, VectorIndex

class Test(models.Model):
    embedding = VectorField(dimensions=3)
    class Meta:
        indexes = [
            VectorIndex(L2Distance("embedding"), name='idx_l2'),
        ]

Create a record

Test.objects.create(embedding=[1, 2, 3])

Get instances with vector field

TiDB supports the following vector distance functions:

  • L1Distance
  • L2Distance
  • CosineDistance
  • NegativeInnerProduct

They can be imported from django_tidb.fields.vector. See Vector Functions and Operators.

Get instances with vector field and calculate distance to a given vector:

from django_tidb.fields.vector import CosineDistance

Test.objects.annotate(distance=CosineDistance('embedding', [3, 1, 2]))

Get instances with vector field and calculate distance to a given vector, and filter by distance:

Test.objects.alias(distance=CosineDistance('embedding', [3, 1, 2])).filter(distance__lt=5)

Supported versions

  • TiDB 6.2 and newer. TiDB before v6.2.0 does not support SAVEPOINT, which Django 4.2 and newer rely on. CI tests the LTS releases from v6.5.
  • TiDB Cloud (see TiDB Cloud release notes):
    • Starter, Essential instances created before June 30, 2026, and Dedicated report TiDB versions such as v8.5.8, the same as self-managed TiDB.
    • Premium and Essential instances created on or after June 30, 2026 run the TiDB X kernel, which reports calendar-based versions such as CLOUD.202603.22. TiDB X CLOUD.202603.1 and newer is supported. django-tidb warns when it connects to an older TiDB X kernel.
  • Django 6.0. For other Django versions, use the matching django-tidb release (see Installing django-tidb).
  • Python 3.12 and newer, as required by Django 6.0.

Test

Create your virtualenv with:

$ python -m venv .venv
$ source .venv/bin/activate

You can use the command deactivate to exit from the virtual environment.

Start TiDB

The tests connect to TiDB at 127.0.0.1:4000 as root without a password (see tidb_settings.py; set TIDB_HOST, TIDB_PORT, TIDB_USER and TIDB_PASSWORD to use another server). Start a local cluster with the same script that CI uses:

$ .github/actions/setup-tidb/start-tidb.sh v8.5.8

The script starts PD, TiKV and TiDB with tiup playground in the background and applies the TiDB settings the test suite needs. It installs TiUP first if tiup is not on your PATH, and it needs the mysql command-line client. The playground log is written to /tmp/tiup-playground.log.

The vector tests also need TiFlash. Pass the number of TiFlash nodes as the second argument:

$ .github/actions/setup-tidb/start-tidb.sh v8.5.8 1

To stop the cluster:

$ pkill -f "tiup playground"

Run the tests

Run all integration tests:

$ DJANGO_VERSION=6.0.10 python run_testing_worker.py

DJANGO_VERSION is a tag or branch of django/django, which is cloned into django_tests_dir. Use the latest patch release of the Django series: 6.0 would check out 6.0.0.

run_testing_worker.py runs every test app listed in django_test_apps.txt, one at a time. To run only some of them, call django_test_suite.sh with DJANGO_TEST_APPS:

$ DJANGO_TEST_APPS="basic delete" DJANGO_VERSION=6.0.10 bash django_test_suite.sh

Migrate from previous versions

Releases on PyPI before 3.0.0 are published from repository https://github.com/blacktear23/django_tidb. This repository is a new implementation and released under versions from 3.0.0. No backwards compatibility is ensured. The most significant points are:

  • Engine name is django_tidb instead of django_tidb.tidb.

Known issues

  • TiDB before v6.6.0 does not support FOREIGN KEY constraints(#18209).
  • TiDB before v6.2.0 does not support SAVEPOINT(#6840).
  • TiDB enforces CHECK constraints only on v7.2.0 or later with the global variable tidb_enable_check_constraint set to ON. It is OFF by default, also on TiDB Cloud. Otherwise, Django doesn't create the CheckConstraints in Meta.constraints and reports models.W027. Turning the variable on later doesn't add the constraints to tables that already exist.
  • TiDB has limited support for default value expressions, please refer to the documentation.

About

TiDB dialect for Django

Topics

Resources

Stars

36 stars

Watchers

29 watching

Forks

Releases

Packages

Used by

Contributors

Languages