Sobes.tech
Junior — Middle

How can you set up and use a database in a Django project?

sobes.tech AI

Answer from AI

In Django, database configuration and usage are done through the project's settings.py file.

  1. In the DATABASES section, connection parameters are specified, for example:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}
  1. After configuration, you need to create model migrations and apply them:
django-admin makemigrations
python manage.py migrate
  1. To work with the database in code, Django ORM models are used:
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
  1. To perform queries:
products = Product.objects.filter(price__gt=100)

Thus, Django simplifies working with the database by providing a convenient ORM and migration tools.