Django Admin: Custom Inline Model FormSet (with non foreign-key relationship)

(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?

-------------Problems Reply------------

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

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:

class TeacherInline(admin.TabularInline):
def __init__(self, parent_model, admin_site):
# override to permit change parent_model from School to Teacher-Parent
# Assume Teacher's parent is Employer
super(TeacherInline, self).__init__(Employer, admin_site)

Category:django Views:0 Time:2011-01-20

Related post

Copyright (C), All Rights Reserved.

processed in 0.111 (s). 11 q(s)