Bird
Raised Fist0
Djangoframework~20 mins

Through model for extra fields on M2M in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Through Model Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of accessing extra fields in a through model?

Consider a Django many-to-many relationship with a through model that adds an extra field date_joined. What will be the output of the following code snippet?

Django
class Membership(models.Model):
    person = models.ForeignKey('Person', on_delete=models.CASCADE)
    group = models.ForeignKey('Group', on_delete=models.CASCADE)
    date_joined = models.DateField()

class Person(models.Model):
    name = models.CharField(max_length=100)
    groups = models.ManyToManyField('Group', through='Membership')

class Group(models.Model):
    name = models.CharField(max_length=100)

# Assume we have a person instance and group instance linked via Membership
membership = Membership.objects.get(person=person_instance, group=group_instance)
print(membership.date_joined)
ARaises DoesNotExist error because Membership is not accessible directly
BPrints the date_joined value stored in the Membership instance
CRaises AttributeError because date_joined is not on Person or Group
DPrints the current date because date_joined defaults to today
Attempts:
2 left
💡 Hint

Remember that the through model stores extra fields and can be queried directly.

state_output
intermediate
1:30remaining
How many Membership records exist after adding a person to a group with extra fields?

Given the following models with a through model Membership that has an extra field role, what is the number of Membership records after executing the code below?

Django
person = Person.objects.create(name='Alice')
group = Group.objects.create(name='Developers')
Membership.objects.create(person=person, group=group, role='admin')
print(Membership.objects.count())
A1
B0
C2
DRaises IntegrityError due to missing fields
Attempts:
2 left
💡 Hint

Creating a Membership instance adds one record.

🔧 Debug
advanced
2:00remaining
Why does this code raise an error when adding to a ManyToManyField with a through model?

Given the models below, why does the code person.groups.add(group_instance) raise an error?

Django
class Membership(models.Model):
    person = models.ForeignKey('Person', on_delete=models.CASCADE)
    group = models.ForeignKey('Group', on_delete=models.CASCADE)
    date_joined = models.DateField()

class Person(models.Model):
    name = models.CharField(max_length=100)
    groups = models.ManyToManyField('Group', through='Membership')

class Group(models.Model):
    name = models.CharField(max_length=100)

person = Person.objects.create(name='Bob')
group_instance = Group.objects.create(name='Admins')
person.groups.add(group_instance)
ABecause person.groups is not a valid attribute
BBecause the group_instance is not saved to the database
CBecause the through model requires extra fields, add() cannot be used without them
DBecause the ManyToManyField is missing related_name
Attempts:
2 left
💡 Hint

Think about how Django handles many-to-many relations with extra fields.

📝 Syntax
advanced
2:30remaining
Which option correctly defines a through model with an extra field for a ManyToManyField?

Choose the correct Django model code that defines a many-to-many relationship with a through model containing an extra field status.

A
class Membership(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    status = models.CharField(max_length=20)

class User(models.Model):
    groups = models.ManyToManyField(Group)
B
class Membership(models.Model):
    user = models.ManyToManyField(User)
    group = models.ManyToManyField(Group)
    status = models.CharField(max_length=20)

class User(models.Model):
    groups = models.ManyToManyField(Group, through='Membership')
C
class Membership(models.Model):
    user = models.ForeignKey(User)
    group = models.ForeignKey(Group)
    status = models.CharField(max_length=20)

class User(models.Model):
    groups = models.ManyToManyField(Group, through='Membership')
D
class Membership(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    status = models.CharField(max_length=20)

class User(models.Model):
    groups = models.ManyToManyField(Group, through='Membership')
Attempts:
2 left
💡 Hint

Remember that ForeignKey fields in the through model require on_delete argument.

🧠 Conceptual
expert
1:30remaining
What is the main advantage of using a through model with extra fields on a ManyToManyField?

Why would a developer choose to use a through model with extra fields instead of a simple ManyToManyField without a through model?

ATo store additional information about the relationship between the two models, such as timestamps or roles
BTo improve database query performance by avoiding joins
CTo automatically create reverse relationships without extra code
DTo allow ManyToManyField to accept more than two models
Attempts:
2 left
💡 Hint

Think about what extra fields in the through model represent.

Practice

(1/5)
1. What is the main purpose of using a through model in a Django many-to-many relationship?
easy
A. To avoid using foreign keys in models
B. To speed up database queries automatically
C. To create a one-to-one relationship instead
D. To add extra fields to the relationship between two models

Solution

  1. Step 1: Understand many-to-many relationships

    A many-to-many field connects two models but by default stores only the link without extra data.
  2. Step 2: Purpose of a through model

    A through model is a separate model that stores the connection plus extra fields about that connection.
  3. Final Answer:

    To add extra fields to the relationship between two models -> Option D
  4. Quick Check:

    Through model = extra fields on M2M [OK]
Hint: Through model = extra info on many-to-many link [OK]
Common Mistakes:
  • Thinking through model speeds up queries
  • Confusing through model with one-to-one relationships
  • Believing through model removes foreign keys
2. Which of the following is the correct way to declare a many-to-many field using a through model named Membership in Django when the Membership model is defined later?
easy
A. members = models.ManyToManyField(User, through='Membership')
B. members = models.ManyToManyField(User, through=Membership())
C. members = models.ManyToManyField(User, through=Membership)
D. members = models.ManyToManyField(User, through='membership')

Solution

  1. Step 1: Syntax for through argument

    The through argument expects the model name as a string if the model is defined later or in the same app.
  2. Step 2: Correct usage

    Using 'Membership' as a string is correct. Passing the class or instance directly is incorrect.
  3. Final Answer:

    members = models.ManyToManyField(User, through='Membership') -> Option A
  4. Quick Check:

    through='ModelName' string syntax [OK]
Hint: Use model name as string in through argument [OK]
Common Mistakes:
  • Passing model class or instance instead of string
  • Using lowercase model name string
  • Omitting the through argument
3. Given the models below, what will print(membership.role) output?
class Group(models.Model):
    name = models.CharField(max_length=100)

class User(models.Model):
    username = models.CharField(max_length=100)

class Membership(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    role = models.CharField(max_length=50)

# Usage
user = User(username='alice')
user.save()
group = Group(name='Developers')
group.save()
membership = Membership(user=user, group=group, role='admin')
membership.save()
print(membership.role)
medium
A. Error: role field missing
B. alice
C. admin
D. Developers

Solution

  1. Step 1: Understand Membership model fields

    Membership has a role field storing a string like 'admin'.
  2. Step 2: Check the saved membership instance

    Membership instance is created with role='admin', so printing membership.role outputs 'admin'.
  3. Final Answer:

    admin -> Option C
  4. Quick Check:

    membership.role = 'admin' [OK]
Hint: Print the extra field on through model instance [OK]
Common Mistakes:
  • Confusing role with user or group fields
  • Expecting username or group name instead
  • Assuming role field is missing
4. What is wrong with this through model declaration?
class User(models.Model):
    username = models.CharField(max_length=100)

class Membership(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey('Group', on_delete=models.CASCADE)
    role = models.CharField(max_length=50)

class Group(models.Model):
    name = models.CharField(max_length=100)
    members = models.ManyToManyField(User, through='Membership')
medium
A. Membership model is declared before Group, causing a NameError
B. No error; this is a valid declaration
C. The through model must be declared after both related models
D. ForeignKey fields in Membership must use related_name

Solution

  1. Step 1: Check model declaration order

    Membership can be declared before Group if the through argument uses string 'Membership'.
  2. Step 2: Validate through usage

    Using through='Membership' is correct and avoids circular import or NameError.
  3. Final Answer:

    No error; this is a valid declaration -> Option B
  4. Quick Check:

    through='ModelName' string allows any order [OK]
Hint: Use string name for through to avoid order errors [OK]
Common Mistakes:
  • Thinking model order causes NameError with string through
  • Believing related_name is mandatory for ForeignKey
  • Assuming through model must be after both models
5. You want to track the date a user joined a group using a through model. Which of these is the best way to add this feature?
hard
A. Add a date_joined = models.DateField() field to the through model and use through='Membership' in the many-to-many field
B. Add a date_joined field directly to the User model
C. Add a date_joined field directly to the Group model
D. Use a signal to store the date_joined in a separate table unrelated to the many-to-many

Solution

  1. Step 1: Identify where to store extra relationship data

    Extra info about the user-group link belongs in the through model, not in User or Group alone.
  2. Step 2: Add date_joined field to through model

    Adding date_joined to Membership and linking with through='Membership' is the correct pattern.
  3. Final Answer:

    Add a date_joined = models.DateField() field to the through model and use through='Membership' -> Option A
  4. Quick Check:

    Extra data on M2M = through model field [OK]
Hint: Extra data on M2M? Put field in through model [OK]
Common Mistakes:
  • Adding extra fields to User or Group instead of through model
  • Using signals unnecessarily for simple data
  • Not linking through model in many-to-many field