0

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"},
}
1

1 Answer 1

1
  • 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", ...},
    ...
  ],
}
Sign up to request clarification or add additional context in comments.

7 Comments

I getting error Got AttributeError when attempting to get a value for field `transfers` on serializer `TransactionSerializer`.
Try specifying the TransactionSerializer meta fields with fields=('created_at','transaction_type_id', 'transfers')
got same error Got AttributeError when attempting to get a value for field `transfers` on serializer `TransactionSerializer
Can you update the models and serializers in your original post?
Please add the related_name='transfers' in the transaction foreign key that is in your transfer model
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.