Make efficient and explicit SQL queries with the Django ORM automatically
Project description
django-orm-plus
A collection of useful ORM features to make using the Django ORM convenient, performant and safe
Installation
pip install django-orm-plus
Now add the following model mixin to your models, eg:
from django.db import models
from django_orm_plus import ORMPlusModelMixin
class MyModel(ORMPlusModelMixin):
name = models.CharField(max_length=10)
Usage
This library has two important functions for use on Django QuerySets:
.strict()
.autofetch()
strict
Strict mode makes sure your ORM queries are efficient and safe by not allowing
related objects to be loaded lazily, therefore select_related
or prefetch_related
must be used if related objects are needed. This avoids
the n+1 query problem.
Strict mode will also raise an error when a deferred field (.defer()
or .only()
)
is accessed.
You only need to add .strict()
to the end of your queryset wherever it's being used.
So for example in a DRF view:
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all().strict()
serializer_class = UserSerializer
permission_classes = [IsAdminUser]
Now your queryset is strict-mode enabled and your view will error if any relations
are loaded for the user queryset eg. users[0].profile
will error if profile
is a foreign key.
To fix, change the query to fetch the relation:
queryset = User.objects.all().select_related("profile").strict()
This will apply for all relations (forward and reverse FKs, many to many, one to one) but not for plain fields.
autofetch
Autofetch combines the two of select_related
and prefetch_related
to reduce the total number of queries for you automatically.
So instead of:
queryset = (
User.objects.all()
.select_related("profile")
.prefetch_related(
"likes",
Prefetch("books", queryset=Book.objects.all().select_related("author")),
)
)
It's now simply:
queryset = User.objects.all().fetch_related("profile", "likes", "books__author")
Of course, the two methods can be used together to get easy and safe queryset evaluation:
queryset = User.objects.all().fetch_related("profile", "likes", "books__author").strict()
Since select_related
does a join in SQL, fetch_related
opts to use select_related
when possible, and in other cases will use prefetch_related
which adds a single additional
query and does the join in python
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for django_orm_plus-0.1.0a0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 4daf19922d6570c62cf75b672ecad2ccf7fc49f28e51fb0afc55fda66478b1e8 |
|
MD5 | 1f29352eea971dd9907f7f223566e961 |
|
BLAKE2b-256 | 6d8046eaf801c53d547a0f4eb5c0a161361dae11716d4d21b122153232c95e3a |