Sobes.tech
Junior — Middle

How to perform table joins using Django ORM?

sobes.tech AI

Answer from AI

In Django ORM, the methods select_related and prefetch_related are commonly used to perform table joins (JOIN) to optimize queries to related models.

  • select_related performs an SQL JOIN and loads related objects in a single query, suitable for ForeignKey and OneToOne relationships.
  • prefetch_related executes a separate query for related objects and joins them in Python, suitable for ManyToMany and reverse relationships.

Example:

# Models
class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

# Get books with authors using JOIN
books = Book.objects.select_related('author').all()
for book in books:
    print(book.title, book.author.name)

If you need to join tables based on an arbitrary condition, you can use annotate with Subquery or extra (an outdated method), but most often, model relationships and select_related/prefetch_related are sufficient.