[英]Django model instance fields with ManyToMany relationship to Dict
[英]Add info to model instance referenced in ManyToMany in Django
從一開始,我就覺得我缺少一些簡單的東西-如果是這樣,請指出正確的方向。 以下是對我的問題的最少解釋:
有期刊,文章和注釋的模型,最后一個代表已發表文章的編輯注釋。 文章完全不能發表,可以在多個期刊上發表; 顯然,期刊可以發表多篇文章。 首先,我們有:
class Article(models.Model):
(author, date of creation, actual text, etc)
class Journal(models.Model):
(edition number, title, staff, etc)
articles = models.ManyToManyField(Article)
到目前為止,這是標准的。 現在,我需要能夠在已發表的文章中添加注釋-假設是簡短的評論或編輯的評論。 注釋需要與單個已發表的文章和某個期刊關聯(同一文章在不同的期刊中可以有不同的注釋)。 最后,注釋可能僅與日記本相關,而不與任何文章相關-在這種情況下,它將代表問題的序言。 到目前為止,我有這個:
class Note(models.Model):
journal = models.ForeignKey(Journal)
article = models.ForeignKey(Article, null=True, blank=True)
text = models.TextField()
(other stuff, irrelevant)
通過這種設置,我們可以確定每個便箋都有日記本參考,並且可能沒有文章參考。 但是,現在可以為未在某些期刊上發表的文章添加注釋,並將其連接到該“錯誤”期刊。 我的頭在旋轉。
如何執行只能與Journal的文章列表中的文章關聯的新筆記的創建? (同樣在django的管理員中-理想情況下,下拉列表應僅顯示所選期刊中的文章)
而且,如何確保每個期刊+文章組合中只有一個筆記(+可能沒有任何文章相關聯)?
這可以通過Form輕松完成。
為確保僅在模型級別有效的選項,需要進行額外的工作。
因此,我推薦這個出色的第三方套餐: django-smart-selects
自述文件中的示例。
from smart_selects.db_fields import ChainedForeignKey
class Location(models.Model):
continent = models.ForeignKey(Continent)
country = ChainedForeignKey(
Country,
chained_field="continent",
chained_model_field="continent",
show_all=False,
auto_choose=True
)
area = ChainedForeignKey(Area, chained_field="country", chained_model_field="country")
city = models.CharField(max_length=50)
street = models.CharField(max_length=100)
我正在生產中使用它,效果很好。 我確實建議設置JQUERY設置以使用較新版本的jQuery。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.