Return a queryset from request data

0

I have the following model:

class Actividad(models.Model):
    nombre = models.TextField()
    es_principal = model.BooleanField()
    fecha_inicio = DateField()
    fecha_fin = DateField()
    dirigente = TextField()

And this is your viewset:

class ActividadViewset(viewsets.ModelViewSet):
    serializer_class = ActividadSerializer
    queryset = Actividad.objects.all()

So far so good, it's a% co_of basic% of viewset and when a request is made GET I return all activities.

Now I need to filter the activities from the data that comes in the request.data . For example, if what you are asking for is the activities according to the name or start date:

def get_queryset(self):
    queryset = Actividad.objects.all()
    nombre = self.request.query_params.get('nombre')
    fecha_inicio = self.request.query_params.get('fecha_inicio')
    if nombre:
        queryset = queryset.filter('nombre' = nombre)
    elif:
        queryset = queryset.filter('fecha_inicio' = fecha_inicio)
    return queryset

My question is how to build the Django Restframework for several cases.

For example:

  • Return activities according to name (ready)
  • Return activities according to start date (ready)
  • Return activities according to name, start date and end date
  • Return activities according to name, start date, end date and if it is main
  • Return activities according to start date, end date and if it is main
  • Return activities according to start date and end date

In another language I would have used a queryset but that does not exist in switch-case . I have to do a if for each of the conditions in the previous list or is there a "dynamic" way to build the Python ? Thanks in advance.

    
asked by Ethan 19.01.2018 в 15:07
source

1 answer

2

I hope you serve my friend

def get_queryset(self):
"""se reciven las variables y las almacenas"""

    nombre = self.request.query_params.get('nombre')
    es_principal = self.request.query_params.get('es_principal')
    fecha_inicio = self.request.query_params.get('fecha_inicio')
    fecha_fin = self.request.query_params.get('fecha_fin')
    dirigente = self.request.query_params.get('dirigente')

    # a las variables almacenadas las guardadas en un diccionario 
    my_filter = {}

    if nombre:
        my_filter["nombre"] = nombre

    if es_principal:
        my_filter["es_principal"] = es_principal

    if fecha_inicio:        
        my_filter["fecha_inicio"] = fecha_inicio

    if fecha_fin:
        my_filter["fecha_fin"] = fecha_fin

    if dirigente:
        my_filter["dirigente"] = dirigente

    # aca creas el query-set y pasas tu diccionario
    queryset = Actividad.objects.filter(**my_filter)

    #retornas el resultado del query-set
    return queryset

##fin
    
answered by 19.01.2018 / 16:34
source