0
0
Djangoframework~10 mins

Model relationships preview in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a one-to-many relationship where each Book belongs to one Author.

Django
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.[1](Author, on_delete=models.CASCADE)
Drag options to blanks, or click blank then click option'
AForeignKey
BManyToManyField
COneToOneField
DCharField
Attempts:
3 left
💡 Hint
Common Mistakes
Using ManyToManyField instead of ForeignKey for one-to-many
Using CharField for relationships
2fill in blank
medium

Complete the code to define a many-to-many relationship between Student and Course.

Django
class Student(models.Model):
    name = models.CharField(max_length=50)
    courses = models.[1](Course)
Drag options to blanks, or click blank then click option'
AManyToManyField
BForeignKey
COneToOneField
DTextField
Attempts:
3 left
💡 Hint
Common Mistakes
Using ForeignKey which only allows one side to have many
Using OneToOneField which restricts to one-to-one
3fill in blank
hard

Fix the error in the code to correctly link Profile to User with a one-to-one relationship.

Django
class Profile(models.Model):
    user = models.[1](User, on_delete=models.CASCADE)
Drag options to blanks, or click blank then click option'
AForeignKey
BOneToOneField
CManyToManyField
DCharField
Attempts:
3 left
💡 Hint
Common Mistakes
Using ForeignKey which allows multiple Profiles per User
Using ManyToManyField which allows many Profiles per User and vice versa
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps each Author's name to the count of their books.

Django
book_counts = {author.name: [1] for author in authors if [2] > 0}
Drag options to blanks, or click blank then click option'
Aauthor.book_set.count()
Bauthor.books.count()
Clen(author.book_set.all())
Dauthor.book_count
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent attribute like author.books
Using len() on a queryset without calling all()
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension mapping each Course's title to the number of enrolled students for courses with more than 2 students.

Django
course_students = {course.[1]: [2] for course in courses if course.students.[3] > 2}
Drag options to blanks, or click blank then click option'
Atitle
Bcourse.students.count()
Ccount()
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using course.name instead of course.title
Forgetting to call count() on the related manager