from django.db import models
class Author(models.Model):
name = models.CharField(max_length=255)
birth_date = models.DateField()
class Book(models.Model):
title = models.CharField(max_length=255)
publication_date = models.DateField()
author = models.ForeignKey(Author, on_delete=models.CASCADE)
# Example Query: Retrieve all books and their authors' names
books_with_authors = Book.objects.values('title', 'author__name')
- Import the necessary modules and classes from Django.
- Define two models,
Author
and Book
, with relevant fields and relationships. - Create a query to retrieve all books along with the names of their authors.
- Use the
values
method on the Book
model to specify the fields to be selected in the query result. - Use the '__' (double underscore) notation to traverse the ForeignKey relationship from the
Book
model to the Author
model and access the 'name' field of the author. - Execute the query and store the result in the
books_with_authors
variable.