Search code examples
pythondjangodjango-autocomplete-light

Django get field from m2m and foreign key


I am adding functionality to my django application to add models(Lot) linked to another(Job) with an M2M field.

The problem:
I am using Django autocomplete light to add this model(Lot) in the form and i want this field to also be filtered by the input and another autocomplete field(Contract), this field is an object called contract that is in the reverse of the M2M field:

Relations:
{Lot}--reverse on the M2M--{Job}--Foreign Key--{Contract}

I am trying to filter lot in the autocomplete to only those where the contract key on the order matches a field in the form, i have looked through documentation and im unsure if there is anyway to do this, below is my latest attempt along with relevant code.

models.py(only fields for the relationship)

class Contract(Parent_model):
    contract_id = models.IntegerField(null=False, default=0000)


class Job(Job_parent):
    contract = models.ForeignKey(Contract, on_delete=models.CASCADE)


class Lot(Job_parent):
    CO = models.ManyToManyField(Job, related_name='Lot') 

autocomplete class based view(views.py)

class lot_auto_complete(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = Lot.objects.all()

        contract_in = self.forwarded.get('contract', None)

        if contract:
            query_set = qs.filter(CO_set.first().contract=contract_in)
        if self.q:
            query_set = qs.filter(lot_number__icontains=self.q)

        return query_set

Solution

  • Don't get me wrong I am not familiar with Django autocomplete light. But it seems that your code has slightly wrong. I think you can get what you want just by doing these:

    # Just change your query
    query_set = qs.objects.filter(CO__contract__contract_id__in=contract_in)
    

    If contract_in list contain only id's. If it contains a list of the contract object then it will look like

    query_set = qs.objects.filter(CO__contract__in=contract_in)