Consider a Django app where each Author can write multiple Books. How does Django model this real-world relationship?
What is the correct way to represent this in Django models?
class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) # What field links Book to Author?
Think about how many books one author can write and how Django links models.
A one-to-many relationship is modeled with ForeignKey in Django. Each book points to one author, but an author can have many books.
In a Django app, Students can enroll in many Courses, and each course can have many students.
What will be the output of student.courses.all() if courses is a ManyToManyField on Student?
class Course(models.Model): name = models.CharField(max_length=100) class Student(models.Model): name = models.CharField(max_length=100) courses = models.ManyToManyField(Course) # Assume student is a Student instance with 2 courses enrolled print(student.courses.all())
Remember what ManyToManyField returns when you call all().
The courses field is a manager for related Course objects. Calling all() returns a QuerySet of enrolled courses.
What error will this Django model code raise?
class Profile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField()Check the required arguments for OneToOneField in Django 3.12+.
Since Django 2.0, on_delete is a required argument for relational fields like OneToOneField. Omitting it causes a TypeError.
Given these models, what will author.book_set.count() output?
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) # Assume author is an Author instance with 3 books linked print(author.book_set.count())
Remember the default related name for ForeignKey reverse lookups.
Django automatically creates a reverse manager named book_set for the ForeignKey. Calling count() returns the number of related Book objects.
Why does this code raise an error?
class Tag(models.Model): name = models.CharField(max_length=50) class Post(models.Model): title = models.CharField(max_length=100) tags = models.ManyToManyField(Tag) post = Post.objects.first() print(post.tags)
Think about what printing a ManyToManyField directly shows.
Printing a ManyToManyField attribute shows the manager object representation, not the related objects. To see related tags, call post.tags.all().