0

I, started using Django REST Framework few days ago, it's a wonderful framework, but I can't find info about this: I serialized my model "Deposito" and I get data in json format succesfully, but I want add some fields like total (total records).

Thanks for your help.

Data obtained with serializers.ModelSerializer

[{
    "id": 78,
    "Numero": "2014051100001",
    "Monto": "100.00",
    "Ingreso": "2014-08-13T22:30:00Z",
    "Entregado": true
},
{
    "id": 533,
    "Numero": "2014051100221",
    "Monto": "200.00",
    "Ingreso": "2014-08-22T14:45:00Z",
    "Entregado": true
}]

Data I want to get

{
    "rows": 
    [{
        "id": 78,
        "Numero": "2014051100001",
        "Monto": "100.00",
        "Ingreso": "2014-08-13T22:30:00Z",
        "Entregado": true
    },
    {
        "id": 533,
        "Numero": "2014051100221",
        "Monto": "200.00",
        "Ingreso": "2014-08-22T14:45:00Z",
        "Entregado": true
    }]
    "total": 2
}

Here is my code

# serializer.py
class DepositosSerializer(serializers.ModelSerializer):
    class Meta:
        model = Deposito
        fields = ('id', 'Numero', 'Monto', 'Ingreso', 'Entregado')


#views.py
def DepositoByClient(request, cliente):
    """
    List Deposito by Cliente.
    """
    try:
        deposito = Deposito.objects.filter(Cliente=cliente, Entregado = True).order_by('Numero')
    except Deposito.DoesNotExist:
        return HttpResponse(status=400)

    if request.method == 'GET':
        serializer = DepositosSerializer(deposito)
        return JSONResponse(serializer.data)

1 Answer 1

2

What's about just adding the total value to the data before returning the response?

#views.py
def DepositoByClient(request, cliente):
    """
    List Deposito by Cliente.
    """
    try:
        deposito = Deposito.objects.filter(Cliente=cliente, Entregado = True).order_by('Numero')
    except Deposito.DoesNotExist:
        return HttpResponse(status=400)

    if request.method == 'GET':
        serializer = DepositosSerializer(deposito)
        rows = serializer.data
        total =  # Whatever you want here ...
        return JSONResponse(dict(rows=rows, total=total))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.