queryset to bring records less than one specific one

1

I have a view based on classes in which I have a function that performs a query in one of the models:

    def get_sympatizers_to_reference(self):
        if self.request.GET.get('q'):
            self.q = self.request.GET.get('q')
            s = Simpatizante.objects.filter(num_documento__contains=self.q).first()
            return [s] if s else None
        else:
            return None

This queryset brings all the records of the model that match the string entered in an input, my question is how can I do so that it does not bring to a specific record in the query.

    
asked by Mauricio Villa 12.08.2017 в 02:09
source

2 answers

0

You can make an exclude for example:

def get_sympatizers_to_reference(self):
    if self.request.GET.get('q'):
        self.q = self.request.GET.get('q')
        s = 
Simpatizante.objects.filter(num_documento__contains=self.q).exclude(id=5).first()
        return [s] if s else None
    else:
        return None

Or you can import Q and do it in the following way:

from django.db.models import Q
def get_sympatizers_to_reference(self):
    if self.request.GET.get('q'):
        self.q = self.request.GET.get('q')
        s = Simpatizante.objects.filter(~Q(id=5), num_documento__contains=self.q).first()
        return [s] if s else None
    else:
        return None
    
answered by 13.08.2017 / 00:54
source
0

If you're looking to not return a specific record, that is, a single record, but bring all records containing that string entered, simply remove the first() . First in English means first, and causes your queryset to return a single record, the first. Try then:

s =  Simpatizante.objects.filter(num_documento__contains=self.q)

On the other hand, the filter method brings many records because this returns a list. It is not necessary then that s is within a new list as you did:

return [s] if s else None

you can directly do:

return s if s else None
    
answered by 14.08.2017 в 00:59