Django Admin:自定义内联模型表单集(具有非外键关系)
(django 1.2.4)
我有两个不同的不相关(它们之间没有外键关系)的django模型。 例如,假设:“学校”和“老师”。
我需要的是,当我在 django 管理界面中打开添加/编辑视图时,“School”对象具有教师对象的内联表单集。显然,这不会是 FK 关系,而是逻辑关系(例如:老师与学校在同一个国家......)。
我需要显示的表格是标准模型表格。 我有一个函数可以为我提供给定学校的教师列表(如果需要则查询集)。
是否有可能实现这样的事情?
(django 1.2.4)
I have two different unrelated (there is no foreign key relationship between them) django models.
For example, let's say: 'School' and 'Teacher'.
What I need is that, when I open add/edit view in django admin interface for 'School' object to have inline formset of Teacher objects. Obiously this won't be FK relationship, but rather logical relationship (example: teachers that are in same country as school...).
Form I need to display is standard model form.
I have a function that would give me list (queryset if needed) of teachers for given school.
Is it possible to implement something like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不完全是我的问题的解决方案,但我最终继承了 ModelAdmin 类并重写了change_view方法,实现了我需要的功能(检索我需要的对象并将它们通过上下文传递给change_form模板,我也扩展了它)。
...并且最终非常喜欢 Django AdminSite 的可扩展性
Not exactlly solution for my problem, but I ended up inheriting ModelAdmin class and overriding change_view method, implementing functionality I needed (retrieving objects I need and passing them through context to change_form template, which I also extended).
... and ended up really liking Django AdminSite extensibility
这样做是否有正当理由值得怀疑。例如,Teacher 拥有 School 的外键是最合乎逻辑的。然而,我最近解决了这个问题,随后意识到这毕竟不是一个好主意。因为有时只需要看到它的表达就可以想到更好的解决方案,所以我提供了解决方案:
将非相关模型作为内联放置时遇到的问题是parent_model 是完全错误的。在本例中,parent_model 是 School,这是不正确的并会导致异常。假设教师有一个真正的父级,解决方案是更正 InlineModelAdmin 子类中的parent_model 字段。您可以通过覆盖 init 函数来做到这一点:
It is doubtful that there is a legitimate reason for doing this. For example, it is most logical for Teacher to have a foreign key to School. However, I recently solved this problem, and subsequently realized it wasn't a good idea after all. Since sometimes it just takes seeing it expressed to think of better solutions, I provide the solution:
The problem you get into putting non-related models as inlines is the parent_model is all wrong. In this case, the parent_model is School, which is incorrect and causes an exception. Assuming Teacher has a real parent, the solution is to correct the parent_model field in your InlineModelAdmin subclass. You can do so by overriding the init func: