How to check request.data variables? DRF

0

I am modifying an API service in Django Rest Framework and I have an error to check if there is a field in the JSON sent by the client.

I have a Comments ViewSet that can be associated to a product or a look, so, in the create() of the service I want to check if the field exists producto create a comment associated with the product and if you do not believe it associated with a look.

My code right now is this:

def create(self, request, *args, **kwargs):
    perfil = Perfil.objects.get(usuario=request.user)
    if request.data['producto']:
        comentario = Comentario.objects.create(perfil= perfil,comentario=request.data['comentario'],ip=obtener_ip(request),
            producto=Producto.objects.get(id=request.data['producto']))
    elif request.data['look']:
        comentario = Comentario.objects.create(perfil= perfil,comentario=request.data['comentario'],ip=obtener_ip(request),
            look=Look.objects.get(id=request.data['look']))
    serializer = ComentarioSerializer(instance=comentario)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

The JSON that I need to send is this:

  

For products: { producto: 1, comentario: "prueba comentario" }

     

For look: { look: 3, comentario: "prueba comentario"}

    
asked by F Delgado 16.04.2018 в 10:13
source

0 answers