Set Django Model Field Choices in your Frontend the Right Way

In Django, you can define a set of choices for any field. If you’re using a SPA frontend, such as React or Vue, then you’ll need to access these choices in a form. Let’s look at two ways to do this. As an example, we’ll use the following Device model: class Device(models.Model): class Size(models.TextChoices): SMALL = "S" MEDIUM = "M" LARGE = "L" name = models.CharField(max_length=255) size = models.CharField(max_length=255, choices=Size.choices) Hardcode choices in frontend The fastest approach is to harcode these choices in the frontend. ...

December 1, 2021 · 2 min · Johnny Metz

5 ways to get all Django objects with a related object

In Django, a related object is a model instance used in the one-to-many or many-to-many context. For example, let’s look at the built-in User model, which has a many-to-many relationship with the Group model. class User(models.Model): groups = models.ManyToManyField(Group, related_name="groups") For any given User object, all linked Group objects are called “related objects”. Here are 5 ways to fetch all User objects with at least one related Group object. Iterate over each object in Python users = [] for user in User.objects.prefetch_related("groups"): if user.groups.exists(): users.append(user) Probably the most popular approach but there are two problems: ...

October 1, 2021 · 2 min · Johnny Metz

Why you need to use Subqueries in Django

The Django ORM is a powerful tool but certain aspects of it are counterintuitive, such as the SQL order of execution. Let’s look at an example of this trap and how we can fix it using subqueries: class Book(models.Model): class Meta: constraints = [ models.UniqueConstraint( fields=["name", "edition"], name="%(app_label)s_%(class)s_unique_name_edition", ) ] name = models.CharField(max_length=255) edition = models.CharField(max_length=255) release_year = models.PositiveIntegerField(null=True) I want to write a query that reads: ...

July 21, 2021 · 2 min · Johnny Metz

Check your Django Migrations on every commit

Keeping your models in sync with your migrations is an important part of any Django app. My team and I frequently make changes to our models and we occassionally forget to create new migrations for those changes. This results in errors and data loss. Let’s look at an easy way to ensure your models and migrations are always in sync: We’ll use a simple Product model. class Product(models.Model): name = models.CharField(max_length=255) Let’s say we want to add a quantity field. ...

May 8, 2021 · 2 min · Johnny Metz

Find all N+1 violations in your Django app

The N+1 problem is a common database performance issue. It plagues ORM’s, such as Django and SQLAlchemy, because it leads to your application making more database queries than necessary. Let’s look at a basic example in Django. class Artist(models.Model): name = models.CharField(max_length=255) class Song(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) name = models.CharField(max_length=255) def print_songs(): for song in Song.objects.all(): print(f"{song.artist.name} - {song.name}") Now let’s create a unit test to ensure print_songs runs successfully. We’re using pytest and pytest-django so we can create the test data using a pytest fixture. When we run the unit test, you’ll notice it passes and our songs are printed to the terminal. Everything seems fine on the surface. ...

April 13, 2021 · 3 min · Johnny Metz