Django built-in admin forms - limiting the number of foreign key requests to a set of values

I have some interconnected models that should coexist on the same admin page. Here's the idea:

In theatrical productions there are participants, and participants in the role have certain roles. Theatrical production is associated with this written text (game, adaptation, etc.), and the written text contains a list of all the roles for this text. When you add Production, each member of the role must be associated with one of these roles.

Here's how the data model works:

Models: Production, Person, CastMember, Role, WrittenText

Relationships: Production and Person have an M2M relationship through CastMember, which adds a "role" field - a ForeignKey object for the role. The role itself has a ForeignKey for the WrittenText object.

So the problem is this: on the admin page for Productions, I have TabularInline to add CastMembers. CastMember records in a table should have a role field limited only by the roles specified in WrittenText that reference Production.

I made a half solution to the problem by overriding the model form:

class CastMemberForm(ModelForm): class Meta: model = CastMember def __init__(self, *args, **kwargs): super(CastMemberForm, self).__init__(*args, **kwargs) if 'instance' in kwargs: self.fields['role'].queryset = Role.objects.filter(source_text=self.instance.production.source_text) 

But this only works if you select Person from the drop-down list, save, and then select the role - otherwise you just get a list of all the roles. The output of the "if" instance in kwargs "gives me a DoNotExistError.

Is it too complicated to do without something like client-side JS, or is there a simpler solution that I am missing?

+1
source share
1 answer

Here is an example of chained select blocks via javascript / ajax. Basically, it should be the same principle, but you need to configure js so as not to update one checkbox, but they are all built in to the administrator ... Perhaps this gives you a little inspiration!

0
source

Source: https://habr.com/ru/post/1341194/


All Articles