通常,參數ForeignKey
limit_choices_to
是您在這種情況下的朋友。 (見https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to)
你可以限制筆者的出席任何事件的用戶列表。然而,即使這樣做是很不理想:
# don't try this at home, this will be excruciatingly slow...
def author_options():
all_attendee_ids = []
for e in Event.objects.all():
for a in e.attendies.all():
all_attendee_ids.append(a.id)
return {'author': Person.objects.filter(id_in=set(all_attendee_ids)).id}
# requires Django 1.7+
class EventArticle(models.Model):
event = models.ForeignKey(Event, related_name='article_event_commentary')
author = models.ForeignKey(Person, limit_choices_to=author_options)
但是,即使你沒有明確說明它在你的問題,我懷疑你希望作者能夠從特定事件被限制在一組參加者的,即與EventArticle模型的事件字段中指定的事件相同。
在這種情況下,這帶來了兩個問題,我不相信可以乾淨地解決:
- 使用limit_choices_to時,你不能傳遞參數(即事件ID)和
- 直到EventArticle模型具有事件的值,您將不知道哪個事件是有問題的。
由於使用limit_choices_to不會在這裏工作,可能沒有辦法來解決這個乾淨。你可以添加到您的EventArticle模型的方法,這將給你像這樣潛在的作者列表...
class EventArticle(models.Model):
event = models.ForeignKey(Event, related_name='article_event_commentary')
author = models.ForeignKey(Person)
def author_options(self):
if self.event:
return self.event.attendies.all()
else:
return []
...但你仍然需要做一些跑腿,使這些可供選擇的UI所以用戶可以選擇它們。不知道更多關於你的設置,我會猜測我是否試圖回答這個問題。