模型
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'
)
序列化器以获取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
如何使用以下json格式返回数据?
最好的方法是什么?
当我尝试运行它时,出现错误“尝试在序列化程序transfers
上获取字段TransactionSerializer
的值时出现AttributeError。”
{
"created_at": "2019-08-18",
"transaction_type_id": "1",
"transfers": {"debit": "100"},
}
答案 0 :(得分:1)
在您的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", ...},
...
],
}