Search code examples
pythondjangoserializationdjango-rest-frameworkjsonserializer

How to return data in custom json format?


Models

class Transaction(models.Model):
    created_at = models.DateTimeField()
    transaction_type = models.ForeignKey(
        TransactionType,
        on_delete=models.CASCADE
    )

class Transfer(models.Model):
    transaction_id = models.ForeignKey(
        Transaction,
        on_delete=models.CASCADE
    )
    debit = models.ForeignKey(
        Account,
        on_delete=models.CASCADE,
        related_name='debit'
    )

Serializers for getting json

class TransferSerializer(serializers.ModelSerializer):
    class Meta:
        model = Transfer
        fields = ('created_at', 'debit',)

class TransactionSerializer(serializers.ModelSerializer):
    transfers = TransferSerializer(many=True)
    class Meta:
        model = Transaction
        fields = ('created_at', 'transaction_type', 'transfers')

Views

class TransactionViewSet(viewsets.ModelViewSet):
    queryset = Transaction.objects.all()
    serializer_class = TransactionSerializer
    pagination_class = LimitOffsetPagination

How to return data with following json format? What is the best approach? When i try to run it i getting error "Got AttributeError when attempting to get a value for field transfers on serializer TransactionSerializer."

{
  "created_at": "2019-08-18",
  "transaction_type_id": "1",
  "transfers": {"debit": "100"},
}

Solution

    • In your Transfer model, in the transaction ForeignKey, add related_name=transfers.

    • In your TransactionSerializer, add the class attribute:

    transfers = TransferSerializer(many=True)
    
    • EDIT: In your TransferSerializer, modify fields for fields=('created_at','transaction_type_id', 'transfers') This will give you:
    {
      "created_at": "2019-08-18",
      "transaction_type_id": "1",
      "transfers": [
        {"transfer_type": 1, "debit": "100", ...},
        ...
      ],
    }