Given these models:
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
And this data:
author1 = Author.objects.create(name='Alice') author2 = Author.objects.create(name='Bob') book = Book.objects.create(title='Django Guide') book.authors.add(author1, author2)
What does book.authors.count() return?
Think about how many authors were added to the book.
The ManyToManyField allows multiple authors per book. Since two authors were added, the count is 2.
Choose the correct syntax to define a many-to-many relationship between Student and Course models.
Remember the exact class name and how to reference related models as strings.
The correct class is ManyToManyField and the related model should be passed as a string if it is defined later or in another file.
Given these models:
class Tag(models.Model):
name = models.CharField(max_length=30)
class Post(models.Model):
title = models.CharField(max_length=100)
tags = models.ManyToManyField(Tag)
And this code:
post = Post.objects.create(title='Hello') post.tags = Tag.objects.filter(name='django')
Why does this raise an error?
Think about how to assign multiple related objects to a ManyToManyField.
You must use set(), add(), or similar methods to assign related objects, not direct assignment.
authors_list after this code runs?Given these models and data:
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
alice = Author.objects.create(name='Alice')
bob = Author.objects.create(name='Bob')
book = Book.objects.create(title='Django Tips')
book.authors.add(alice, bob)
authors_list = list(book.authors.values_list('name', flat=True))
What is authors_list?
Think about what values_list('name', flat=True) returns.
This returns a list of author names related to the book. Since both Alice and Bob were added, both names appear.
Choose the correct statement about how Django handles ManyToManyField relationships internally.
Think about how relational databases handle many-to-many relationships.
Django automatically creates a join table to link the two models unless you specify your own through model.