如何以自定义 json 格式 return 数据?

How to return data in custom json format?

型号

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 用于获取 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')

观看次数

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

如何return数据格式如下json? 什么是最好的方法? 当我尝试 运行 时,出现错误 "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"},
}
  • 在您的 Transfer 模型中,在事务 ForeignKey 中,添加 related_name=transfers.

  • 在您的 TransactionSerializer 中,添加 class 属性:

transfers = TransferSerializer(many=True)
  • 编辑:在您的 TransferSerializer 中,将 fields 修改为 fields=('created_at','transaction_type_id', 'transfers') 这会给你:
{
  "created_at": "2019-08-18",
  "transaction_type_id": "1",
  "transfers": [
    {"transfer_type": 1, "debit": "100", ...},
    ...
  ],
}