49
有沒有辦法告訴Django具有內容類型的模型GenericForeignKey只能指向預定義列表中的模型?例如,我有4個模型:A,B,C,D和一個包含GenericForeignKey的模型X.我可以告訴X只有A & B被允許用於GenericForeignKey嗎?如何限制Django的GenericForeignKey到模型列表?
有沒有辦法告訴Django具有內容類型的模型GenericForeignKey只能指向預定義列表中的模型?例如,我有4個模型:A,B,C,D和一個包含GenericForeignKey的模型X.我可以告訴X只有A & B被允許用於GenericForeignKey嗎?如何限制Django的GenericForeignKey到模型列表?
例如, 您的應用程序是app和app2,應用程序中有A,B模型,app2中有C,D模型。 你只想看到app.A和app.B和app2.C
class TaggedItem(models.Model):
tag = models.SlugField()
limit = models.Q(app_label = 'app', model = 'a') | models.Q(app_label = 'app', model = 'b') | models.Q(app_label = 'app2', model = 'c')
content_type = models.ForeignKey(ContentType, limit_choices_to = limit)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
上ForeignKey的使用limit_choices_to。
查看django文檔以獲取詳細信息和Q對象app_label。 你需要編寫適當的app_label和model。這只是代碼片段
加:我想你寫錯了app_label。這可以幫助你。
from django.contrib.contenttypes.models import ContentType
for c in ContentType.objects.all():
print(c.app_label, c.model)
但是,管理界面似乎並沒有使用它,因爲它是選擇領域。這是爲什麼? – Geo 2011-06-13 22:16:47
我在管理員端進行了檢查,並按照預期與默認管理員一起工作。也許你在那裏做了一些小錯字。我不知道你的問題。 – mumino 2011-06-13 22:56:10
在我的管理員中,在添加限制後,GenericForeignKey選擇的選項消失。我只剩下「---」。您可以發佈一個屏幕截圖與您的管理員的選擇? – Geo 2011-06-14 06:36:31