🗄models

Best practice of models

Moving to Django 3.0's Field.choices Enumeration Types:

from django.db import models

class Book(models.Model):
    UNPUBLISHED = 'UN'
    PUBLISHED = 'PB'
    STATUS_CHOICES = [
        (UNPUBLISHED, 'Unpublished'),
        (PUBLISHED, 'Published'),
    ]
    status = models.CharField(
        max_length=2,
        choices=STATUS_CHOICES,
        default=UNPUBLISHED,
    )


# QuerySet filters 
# unpublished_books = Book.objects.filter(status=Book.UNPUBLISHED)

Queryset Results as namedtuple

Custom Funtions

Statement Timeout

Select for update ... of

FK indexes

In the model above Django will implicitly create two indexes - one for user and one for group. The unique_together will also create an index on both fields. Wo we get one model with two fields and three indexes.

Removing redundant indexes will make insert and updates faster, plus, our database is now lighter which is always a good thing. make the secondary indexes as small as possible. it's reasonable to assume there are more users than groups so putting the user column first will make the secondary index on group, smaller.

BRIN indexes

BRIN indexes can be more efficient then B-Tree indexes. The disadvantage of B-Tree index is it's size - B-Tree indexes can get big.

Last updated

Was this helpful?