Inne zaawansowane operacje na modelach: 205:

205. Jak stworzyć dodatkowe indeksy kiedy chcesz szybciej filtrować dane używając specyficznych pól?
    # 1. Dodanie indeksów za pomocą indexes w klasie Meta:
    
    from django.db import models
    
    class Book(models.Model):
        title = models.CharField(max_length=200)
        author = models.CharField(max_length=100)
        publication_date = models.DateField()
    
        class Meta:
            indexes = [
                models.Index(fields=['author']),  # Indeks na polu 'author'
                models.Index(fields=['-publication_date', 'author']),  # Indeks na wielu polach
            ]
    
    
    2. Dodanie unikalnych indeksów za pomocą unique_together lub UniqueConstraint:
    from django.db import models
    
    class Book(models.Model):
        title = models.CharField(max_length=200)
        author = models.CharField(max_length=100)
        publication_date = models.DateField()
    
        class Meta:
            constraints = [
                models.UniqueConstraint(fields=['title', 'author'], name='unique_title_author'),
            ]
    
    3. Użycie indeksów funkcyjnych (expressions):
    
    from django.db import models
    from django.db.models import Index
    from django.db.models.functions import Lower
    
    class Book(models.Model):
        title = models.CharField(max_length=200)
        author = models.CharField(max_length=100)
    
        class Meta:
            indexes = [
                Index(Lower('title'), name='lower_title_idx'),  # Indeks na znormalizowanym (małe litery) polu 'title'
            ]