Connect to TiDB with Django

TiDB is a MySQL-compatible database, and Django is a popular web framework for Python, which includes a powerful Object Relational Mapper (ORM) library.

In this tutorial, you can learn how to use TiDB and Django to accomplish the following tasks:

  • Set up your environment.
  • Connect to your TiDB cluster using Django.
  • Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations.

Django - 图1

Note

This tutorial works with TiDB Serverless, TiDB Dedicated, and TiDB Self-Hosted clusters.

Prerequisites

To complete this tutorial, you need:

If you don’t have a TiDB cluster, you can create one as follows:

If you don’t have a TiDB cluster, you can create one as follows:

Run the sample app to connect to TiDB

This section demonstrates how to run the sample application code and connect to TiDB.

Step 1: Clone the sample app repository

Run the following commands in your terminal window to clone the sample code repository:

  1. git clone https://github.com/tidb-samples/tidb-python-django-quickstart.git
  2. cd tidb-python-django-quickstart

Step 2: Install dependencies

Run the following command to install the required packages (including Django, django-tidb, and mysqlclient) for the sample app:

  1. pip install -r requirements.txt

If you encounter installation issues with mysqlclient, refer to the mysqlclient official documentation.

What is django-tidb?

django-tidb is a TiDB dialect for Django that resolves compatibility issues between TiDB and Django.

To install django-tidb, choose a version that matches your Django version. For example, if you are using django==4.2.*, install django-tidb==4.2.*. The minor version does not need to be the same. It is recommended to use the latest minor version.

For more information, refer to django-tidb repository.

Step 3: Configure connection information

Connect to your TiDB cluster depending on the TiDB deployment option you’ve selected.

  • TiDB Serverless
  • TiDB Dedicated
  • TiDB Self-Hosted
  1. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

  2. Click Connect in the upper-right corner. A connection dialog is displayed.

  3. Ensure the configurations in the connection dialog match your operating environment.

    • Endpoint Type is set to Public
    • Branch is set to main
    • Connect With is set to General
    • Operating System matches your environment.

    Django - 图2

    Tip

    If your program is running in Windows Subsystem for Linux (WSL), switch to the corresponding Linux distribution.

  4. Click Generate Password to create a random password.

    Django - 图3

    Tip

    If you have created a password before, you can either use the original password or click Reset Password to generate a new one.

  5. Run the following command to copy .env.example and rename it to .env:

    1. cp .env.example .env
  6. Copy and paste the corresponding connection string into the .env file. The example result is as follows:

    1. TIDB_HOST='{host}' # e.g. gateway01.ap-northeast-1.prod.aws.tidbcloud.com
    2. TIDB_PORT='4000'
    3. TIDB_USER='{user}' # e.g. xxxxxx.root
    4. TIDB_PASSWORD='{password}'
    5. TIDB_DB_NAME='test'
    6. CA_PATH='{ssl_ca}' # e.g. /etc/ssl/certs/ca-certificates.crt (Debian / Ubuntu / Arch)

    Be sure to replace the placeholders {} with the connection parameters obtained from the connection dialog.

    TiDB Serverless requires a secure connection. Since the ssl_mode of mysqlclient defaults to PREFERRED, you don’t need to manually specify CA_PATH. Just leave it empty. But if you have a special reason to specify CA_PATH manually, you can refer to the TLS connections to TiDB Serverless to get the certificate paths for different operating systems.

  7. Save the .env file.

  8. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

  9. Click Connect in the upper-right corner. A connection dialog is displayed.

  10. Click Allow Access from Anywhere and then click Download CA cert to download the CA certificate.

    For more details about how to obtain the connection string, refer to TiDB Dedicated standard connection.

  11. Run the following command to copy .env.example and rename it to .env:

    1. cp .env.example .env
  12. Copy and paste the corresponding connection string into the .env file. The example result is as follows:

    1. TIDB_HOST='{host}' # e.g. tidb.xxxx.clusters.tidb-cloud.com
    2. TIDB_PORT='4000'
    3. TIDB_USER='{user}' # e.g. root
    4. TIDB_PASSWORD='{password}'
    5. TIDB_DB_NAME='test'
    6. CA_PATH='{your-downloaded-ca-path}'

    Be sure to replace the placeholders {} with the connection parameters obtained from the connection dialog, and configure CA_PATH with the certificate path downloaded in the previous step.

  13. Save the .env file.

  14. Run the following command to copy .env.example and rename it to .env:

    1. cp .env.example .env
  15. Copy and paste the corresponding connection string into the .env file. The example result is as follows:

    1. TIDB_HOST='{tidb_server_host}'
    2. TIDB_PORT='4000'
    3. TIDB_USER='root'
    4. TIDB_PASSWORD='{password}'
    5. TIDB_DB_NAME='test'

    Be sure to replace the placeholders {} with the connection parameters, and remove the CA_PATH line. If you are running TiDB locally, the default host address is 127.0.0.1, and the password is empty.

  16. Save the .env file.

Step 4: Initialize the database

In the root directory of the project, run the following command to initialize the database:

  1. python manage.py migrate

Step 5: Run the sample application

  1. Run the application in the development mode:

    1. python manage.py runserver

    The application runs on port 8000 by default. To use a different port, you can append the port number to the command. The following is an example:

    1. python manage.py runserver 8080
  2. To access the application, open your browser and go to http://localhost:8000/. In the sample application, you can:

    • Create a new player.
    • Bulk create players.
    • View all players.
    • Update a player.
    • Delete a player.
    • Trade goods between two players.

Sample code snippets

You can refer to the following sample code snippets to complete your own application development.

For complete sample code and how to run it, check out the tidb-samples/tidb-python-django-quickstart repository.

Connect to TiDB

In the file sample_project/settings.py, add the following configurations:

  1. DATABASES = {
  2. "default": {
  3. "ENGINE": "django_tidb",
  4. "HOST": ${tidb_host},
  5. "PORT": ${tidb_port},
  6. "USER": ${tidb_user},
  7. "PASSWORD": ${tidb_password},
  8. "NAME": ${tidb_db_name},
  9. "OPTIONS": {
  10. "charset": "utf8mb4",
  11. },
  12. }
  13. }
  14. TIDB_CA_PATH = ${ca_path}
  15. if TIDB_CA_PATH:
  16. DATABASES["default"]["OPTIONS"]["ssl_mode"] = "VERIFY_IDENTITY"
  17. DATABASES["default"]["OPTIONS"]["ssl"] = {
  18. "ca": TIDB_CA_PATH,
  19. }

You need to replace ${tidb_host}, ${tidb_port}, ${tidb_user}, ${tidb_password}, ${tidb_db_name}, and ${ca_path} with the actual values of your TiDB cluster.

Define the data model

  1. from django.db import models
  2. class Player(models.Model):
  3. name = models.CharField(max_length=32, blank=False, null=False)
  4. coins = models.IntegerField(default=100)
  5. goods = models.IntegerField(default=1)
  6. created_at = models.DateTimeField(auto_now_add=True)
  7. updated_at = models.DateTimeField(auto_now=True)

For more information, refer to Django models.

Insert data

  1. # insert a single object
  2. player = Player.objects.create(name="player1", coins=100, goods=1)
  3. # bulk insert multiple objects
  4. Player.objects.bulk_create([
  5. Player(name="player1", coins=100, goods=1),
  6. Player(name="player2", coins=200, goods=2),
  7. Player(name="player3", coins=300, goods=3),
  8. ])

For more information, refer to Insert data.

Query data

  1. # get a single object
  2. player = Player.objects.get(name="player1")
  3. # get multiple objects
  4. filtered_players = Player.objects.filter(name="player1")
  5. # get all objects
  6. all_players = Player.objects.all()

For more information, refer to Query data.

Update data

  1. # update a single object
  2. player = Player.objects.get(name="player1")
  3. player.coins = 200
  4. player.save()
  5. # update multiple objects
  6. Player.objects.filter(coins=100).update(coins=200)

For more information, refer to Update data.

Delete data

  1. # delete a single object
  2. player = Player.objects.get(name="player1")
  3. player.delete()
  4. # delete multiple objects
  5. Player.objects.filter(coins=100).delete()

For more information, refer to Delete data.

Next steps

Need help?

Ask questions on the Discord, or create a support ticket.