0

I'm relatively new to Django, and I've been trying to find a way to implement a ManyToMany field whose visible 'choices' within the UI change based upon a BooleanField found within the same model.

For instance, suppose I have a model that represents different jobs, and a worker model that has a manytomany relationship to this jobs model. Suppose also that there are two types of workers: a manager and non-manager which is represented as a BooleanField. If you are a manager, you have certain jobs that a worker does not have and vice versa.

I'm trying to find a way, without creating a new table, to have it such that the jobs listed within the manytomany relationship are dependent on the boolean value of 'is_manager'. That is, if you were to click 'is_manager', this should list manager-specific jobs, yet these manager specific jobs live within the same table as non-manager jobs -- those would just be blank.

I've been looking into the through field, etc, but all solutions that I come up with seem to be dependent on making another table. I'm sure there is a way to do this better though.

Thank you.

Akbk
  • 1
  • I am a big confused. What you describe does not seem related to the model but mostly it is about frontend. How are you creating the form? – Simone Zandara Nov 25 '15 at 22:51
  • What do you mean by "making a table"? Are you managing your database manually for some reason? Also, my intuition is that the solution to your problem may lie in creating a custom "RelatedManager" for your many to many field. See https://docs.djangoproject.com/en/dev/topics/db/managers/#manager-types, but also, @xbirkettx makes a valid point... What do you mean by "within the UI"? If you are referring to the Django admin, then my solution may help, but if you mean on the frontend of a web page, there are many tools at your disposal to limit this on the front end rather than in the database. – Isaac Ray Nov 25 '15 at 23:00

1 Answers1

0

I suggest this approach:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['jobs', 'username']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        instance = kwargs.get('instance', None)
        if instance is not None:
            if instance.is_manager:
                self.fields['jobs'].queryset = Jobs.objects.filter(manager=True)
            else:
                self.fields['jobs'].queryset = Jobs.objects.filter(manager=False)
Alex Polekha
  • 1,590
  • 15
  • 13