您可以使用許多一對多的關係,即自動創建爲你中間模型:對many to many
publication.articles.all() # Gives you the articles of the current publication instance
article.publications.all() # Gives you the publications of the current article instance
退房文檔:
from django.db import models
class Publication(models.Model):
title = models.CharField(max_length=30)
class Article(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication, related_name='articles')
有了這個,你都可以做
如果您需要使用該中間模型中的任何其他字段,您可以告訴django這是through
型號,如下所示:
個
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
退房文檔的extra fields on many to many
此外,如果你要一個標準的整數自動增量的主鍵,Django的已經產生了一個給你,這樣你就不需要定義id_A
和id_B
。
好吧,我正要找到關於related_name屬性的答案,但你已經回答了我!謝謝! – Hari