ManyToManyField und Through-Modelle
Datensätze mit zusätzlichen Daten in beide Richtungen verknüpfen
ManyToManyField und Through-Modelle ist eine kostenlose Django Academy-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Django Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Django Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
Both Sides Have Many
Sometimes each side links to many of the other: a post has many tags, a tag marks many posts. That is a many-to-many relationship.
Declaring ManyToManyField
Add a ManyToManyField pointing at the other model. Django handles the link from both directions automatically.
class Post(models.Model):
tags = models.ManyToManyField(Tag)The Hidden Join Table
Behind the scenes Django builds a join table holding pairs of ids. No new column lands on either of your two models.
Adding Relations
Once a post is saved, attach tags with add. You can pass several objects at once in a single call.
post.tags.add(python_tag, web_tag)Removing and Clearing
Drop a single link with remove, or wipe them all with clear. The related objects themselves stay safe.
post.tags.remove(web_tag)
post.tags.clear()Reading the Set
Access linked rows through the field like a normal manager. Call all to loop over everything connected.
for tag in post.tags.all():
print(tag.name)When the Link Needs Data
What if a membership has its own facts, like a join date? A plain join table cannot hold extra columns, so you need more control.
The through Model
A through model is your own table for the relationship. It lets each link carry extra fields you define.
members = models.ManyToManyField(User, through="Membership")Defining the through Class
The through model holds a ForeignKey to each side plus any extra fields. Those columns describe the connection itself.
class Membership(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
joined = models.DateField()add Stops Working
With a custom through model, plain add is disabled. You create the link by making a through row directly instead.
Membership.objects.create(user=u, group=g, joined=today)Querying Across M2M
Filter through a many-to-many link with the double underscore, just like a ForeignKey. The join table is handled for you.
Post.objects.filter(tags__name="python")Quick Check
Your group membership needs to record when each user joined. What do you reach for?
Recap
Well done! A ManyToManyField links both sides freely, and a through model lets each connection carry its own data. 🏷️
Häufig gestellte Fragen
Ist die Lektion „ManyToManyField und Through-Modelle“ kostenlos?
Ja — der vollständige Text von „ManyToManyField und Through-Modelle“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Django Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Django Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „ManyToManyField und Through-Modelle“?
Datensätze mit zusätzlichen Daten in beide Richtungen verknüpfen Du übst Django Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Django Academy zu starten?
Keine Vorkenntnisse erforderlich. Django Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.
Wie lange dauert die Lektion „ManyToManyField und Through-Modelle“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Django Academy-Lektion Code schreiben und ausführen?
Ja. Jede Django Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- ForeignKey und on_delete
- ManyToManyField und Through-Modelle
- OneToOneField für Profile
- related_name und umgekehrte Lookups