ManyToManyFieldとThrough Models
追加データを持たせてレコード同士を双方向に関連付けます
「ManyToManyFieldとThrough Models」はCoddyKit上の無料Django Academyレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはDjango Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Django Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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. 🏷️
よくある質問
「ManyToManyFieldとThrough Models」レッスンは無料ですか?
はい。「ManyToManyFieldとThrough Models」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Django Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Django Academyコースには全4レッスンが含まれています。
「ManyToManyFieldとThrough Models」で何を学びますか?
追加データを持たせてレコード同士を双方向に関連付けます ブラウザで直接実行するハンズオンコードでDjango Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Django Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのDjango Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「ManyToManyFieldとThrough Models」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このDjango Academyレッスンでコードを書いて実行できますか?
はい。すべてのDjango Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- ForeignKeyとon_delete
- ManyToManyFieldとThrough Models
- Profiles用のOneToOneField
- related_nameと逆引き