jjulian91
jjulian91

Reputation: 41

Django ManyToMany relationship, filter options of modelmultiplechoicefield

I am currently rewriting a web app that is utilizing a hierarchy of relationships which is making it extremely painful to create a reliable work flow for the creation of objects. The current set up is as follows:

Customer Hierarchy:

Organization -> Location -> Room

Contacts can belong to one or many of these entries at any level of the hierarchy. Ex Jim can be assigned to Organization and location.

With this I need to filter the django many to many field that is populated with any contact that doesn't belong anywhere OR belongs to a parent or child level of the customer hierarchy.

I have attempted inline formsets which fails on the many to many model as well as limit_choices_to={'Organization':_get_self_pk} . This works but doesn't allow for the use of django admin style on the fly creation of contacts. I have also attempted to use a queryset in the init function for create, but my form has a nested inline formset that doesn't allow me to use the self.field['contact'] to inject the queryset. (Key Error, contacts doesn't exist as a field)

Models.py

class Organization(AbstractExclusions, AbstractManyToManyCommonInfo, AbstractCommonInfo, AbstractOrganizationLocationCommonInfo, AbstractAcvitivyInfo):
               ....
               contact = models.ManyToManyField('Contact', blank=True)
 

class Location(AbstractManyToManyCommonInfo, AbstractCommonInfo, AbstractOrganizationLocationCommonInfo, AbstractLocationRoomCommonInfo, AbstractAcvitivyInfo, AbstractExclusions):
                ....
                contact = models.ManyToManyField('Contact', blank=True)
            
class Room(AbstractManyToManyCommonInfo, AbstractCommonInfo, AbstractLocationRoomCommonInfo, AbstractAcvitivyInfo, AbstractExclusions):
                ....
                contact = models.ManyToManyField('Contact', blank=True)
            
class Contact(AbstractUserInfo):
                phone_number = PhoneNumberField(verbose_name=_('Phone Number'))
                is_user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True,  on_delete=models.CASCADE, verbose_name=_('Link To Authenticated User'),)
                role = models.ForeignKey(refModels.Role, verbose_name=_("Role"), on_delete=models.CASCADE, null=True, blank=True)

Upvotes: 0

Views: 133

Answers (1)

jjulian91
jjulian91

Reputation: 41

This question was answered by creating a special init function as shown below:

def __init__(self, *args, **kwargs):
super(OrganizationForm, self).__init__(*args, **kwargs)
if 'initial' in kwargs:
    try:
        self.fields['contact'].queryset = (custModels.Contact.objects.filter(Q(organization = None) | Q(organization = self.instance.id)))
    except:
        pass

Upvotes: 1

Related Questions