filter to get the contents of a Django list?

1

I hope it is not a little trivial my question I have the following models.

class ModelA(models.Model):
     tipo= UCharField(max_length=20, null=True, blank=True)

class  ModelB(models.Model):
     model_a= models.ForeignKey(ModelA, null=False, blank=False,related_name='modelA_%(class)s_objects')

I need to obtain the records contained in the following array:

list_id= list(ModelA.objects.filter(tipo= 1).values_list('id', flat=True)) 
ModelB.objects.filter(modal_a_id__in = list_id)

It turns out that "IN" returns if it found any of the values of the array, I require that it yield results when all the ids of the array are contained in the ModelB model. I could do an iteration for each value in the array and check if it exists, any suggestions to do it in a simpler way ??

    
asked by Alexander Morales 11.10.2016 в 23:21
source

2 answers

1
def get_queryset(self):
list_id = get_objcet_or_404(ModelA, tipo=self.kwargs['....']
modelob = ModelB.objects.filter(modal_a = list_id)
return modelob

the kwargs you add to the urls as patterns and it will filter you by list

Another option would be:

def get_queryset(self):
if self.kwarg.get('....'):
queryset = self.model.objects.filter(model_a__tipo=self.kwargs['....'])
else:
queryset = super(NOMBRE DE LA CLASE DE LA VISTA, self).get_queryset
return queryset

I hope it serves you and solve your doubt, greetings, I forgot. in the second option you have to add the field in case there is nothing:

model = ModelB
    
answered by 12.10.2016 в 15:32
1

You can try this:

import operator
from django.db.models import Q

list_id= list(ModelA.objects.filter(tipo= 1).values_list('id', flat=True)) 
query = reduce(operator.and_, (Q(model_a=id) for id in list_id))
result = ModelB.objects.filter(query)
    
answered by 14.10.2016 в 07:42