我有一个表格,希望显示拟议投资的多个养老基金的提用金额。我已经在表中的“投资”实例上编写了一个for循环。但是,我似乎无法从此循环中检索到金额。我认为我的queryset'amountdrawdown'是不正确的,因为我正试图反向查找外键(从Investment模型到DrawdownOnFund模型)。
我的models.py,简化了:
class PensionFund(models.Model):
name = models.CharField()
class PensionFundDeposit(models.Model):
PensionFund = models.ForeignKey(PensionFund)
date = models.DateField()
amount = models.DecimalField()
undrawn = models.DecimalField()
class Investment(models.Model): <---- Looping over this
amount = models.DecimalField()
date = models.DateField()
class DrawdownOnFund(models.Model):
Investment = models.ForeignKey(Investment)
PensionFund = models.ForeignKey(PensionFund)
date = models.DateField()
amount = models.DecimalField() <---- I would like to retrieve this
我的serializer.py,简化了:
class PensionFundSerializer(serializers.ModelSerializer):
class Meta:
fields = ['id', 'name']
class PensionFundDepositSerializer(serializers.ModelSerializer):
class Meta:
fields = ['id', 'fund','date','amount','undrawn', 'fundname']
class InvestmentSerializer(serializers.ModelSerializer):
amountdrawdown = serializers.CharField(source='drawdown.amount') <---My attempt to write a query to retrieve the amount
class Meta:
fields = ['id', 'amount', 'date', 'amountdrawdown']
class DrawdownOnFundSerializer(serializers.ModelSerializer):
class Meta:
fields = ['id', 'call', 'commitment', 'date', 'amount', 'callid']
答案 0 :(得分:1)
Investment
-> DrawdownOnFund
具有1-Many关系。因此,DrawdownonFund
将与Investment
实例之一相关。并且,在反向类中(即Investment
)将有一个DrawdownOnFund
实例的列表,其反向查找字段的名称为drawdownonfund_set
(默认情况下)。
因此,考虑到这种情况,您想要显示与一项投资相关的所有提款资金的清单,您应该使用嵌套的序列化器模式。
class DrawdownOnFundSerializer(serializers.ModelSerializer):
class Meta:
fields = ['id', 'call', 'commitment', 'date', 'amount', 'callid']
class InvestmentSerializer(serializers.ModelSerializer):
amountdrawdowns = DrawdownOnFundSerializer(many=True, source='drawdownonfund_set')
class Meta:
fields = ['id', 'amount', 'date', 'amountdrawdowns']
对Investment
模型的一个实例进行反序列化输出将如下所示。
您可以通过管理amountdrawdowns
来控制DrawdownOnFundSerializer
中每个项目的显示字段。
{
"id": "1",
"amount": "",
"date": "",
"amountdrawdowns": [
{
"id": "",
"call": "",
"commitment": "",
"date": "",
"amount": "",
"callid": ""
}
]
}