Sobes.tech
Junior — Middle

How can data be combined from multiple tables in Django using ORM?

sobes.tech AI

Answer from AI

In Django ORM, to combine data from multiple tables, model relationships and methods like select_related and prefetch_related are typically used to optimize queries.

If models are related through ForeignKey, related objects can be retrieved using select_related (for "eager" loading of related objects):

# 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)

# Fetching books with authors in a single query
books = Book.objects.select_related('author').all()
for book in books:
    print(book.title, book.author.name)

For ManyToMany or reverse relations, prefetch_related is used.

You can also use annotate and aggregate to combine and compute data from related tables.

If you need to combine data from unrelated models, you can use union() or write raw SQL queries via raw().