Search code examples
python-3.xserializationdjango-rest-frameworknestedresponse

DRF how to return multiple datas inside the same serializer


I will try to make my problem as simple as possible:

I have this serializer:

class DatesSerializer(serializers.Serializer):
    date = serializers.CharField(max_length=10)
    ... bunch of stuff and Others serializers

and on my view.py I have this piece of code:

dates = ["2021-05-02", "2021-06-28", "2021-07-02"]
...
for date in dates:
    faults = DatesSerializer({
         "date":date,
         ...
    })
return Response({"faults":faults.data, status=200})

I receive a response like these:

{
 "faults":{
            "date":"2021-07-02"
            ....
          }
}

what I wanted was a response like this one

{
 "faults":{
            "date":"2021-07-02"
            ....
          },
          {
            "date":"2021-06-28"
            ....
          },              {
            "date":"2021-05-02"
            ....
          }
}

I understand that on my loop I'm overwriting my serializer and that's why I just have the last entry, but I have tried to overcome this by adding on a dict and got nowhere since the key will always be the same, and I'm stuck on how to fix this


Solution

  • What you want is not a valid object. You want a list, and this easily can be accomplished in a loop by appending serializer data on each iteration.

    res = []
    
    for date in dates:
        serializer = DatesSerializer({
             "date":date,
             ...
        })
        res.append(serializer.data)
    return Response({ "faults": res }, status=200)