How to filter in a serializer?

1

Hello, good morning, I want to obtain in a webservice / Api all the appraisals depending on the agency, I'll leave them as I have until now

These are my models

class Agencia(models.Model):
nombre = models.CharField(max_length=50,)
razon_social = models.CharField(max_length=50)
rfc = models.CharField(max_length=15)
direccion = models.CharField(max_length=50)
logo= models.ImageField(upload_to='logo/images/')

def __unicode__(self):
    return self.nombre

class Usuarios(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
Agencia = models.ForeignKey('Agencia',null=True,blank=True)

def __unicode__(self):
    return self.Agencia

class Avaluo(models.Model):
coche = models.OneToOneField(Autoss,null=True,blank=True,on_delete=models.CASCADE)
lugar = models.CharField(max_length=40)
fecha_visita = models.DateTimeField()
valuador = models.ForeignKey(Usuarios,blank=True,null=True)
Estatus = models.BooleanField(default=False)

def __unicode__(self):
    return self.lugar

Serializer:

class usuarioAgencia(serializers.ModelSerializer):
class Meta:
    model = Usuarios
    fields = '__all__'

Viewset:

class UsuarioAgenciaViewSet(viewsets.ModelViewSet):
serializer_class = usuarioAgencia
queryset = Usuarios.objects.all()

What I want is that when I show the results I filter them by the agencies I do not know what they recommend me to do

    
asked by Angel 06.04.2016 в 19:56
source

1 answer

1

Assuming you are using Django Rest Framework , you could add the filters in the queryset of your ModelViewSet . Something similar to this:

from django.shortcuts import get_object_or_404

def get_queryset(self):
    queryset = self.queryset
      agencia_id = self.request.query_params.get('agencia', None)
      if agencia_id is not None:
          agencia_instance = get_object_or_404(Agencia, id=agencia_id)
          queryset = queryset.filter(agencia=agencia_instance)
      return queryset

With your Viewset remaining such that:

class UsuarioAgenciaViewSet(viewsets.ModelViewSet):
    serializer_class = usuarioAgencia
    queryset = Usuarios.objects.all()

    def get_queryset(self):
        queryset = self.queryset
          agencia_id = self.request.query_params.get('agencia', None)
          if agencia_id is not None:
              agencia_instance = get_object_or_404(Agencia, id=agencia_id)
              queryset = queryset.filter(agencia=agencia_instance)
          return queryset

In the official documentation you can find many more examples of how to filter on Views.

Finally, you can use this extension of Django Rest Framework to be able to use filters with parameters like it was a list of Django Admin

Important: In this example I used djangorestframework==3.3.3 . It may be a little different in previous versions.

    
answered by 19.09.2016 в 16:46