[英]Append values to serializer data
我正在从 API 获取一些客户信用卡。 数据并不表示客户的“默认”卡,尽管另一个 API 可以做到这一点。 我想过滤第一个数据集并添加一个值,指示该卡是否与默认卡匹配。
customer = Customer.objects.get(subscriber=request.user.organization_id)
default_payment_method = customer.default_payment_method.organization_id
cards = PaymentMethod.objects.filter(customer=customer.djstripe_id)
serializer = PaymentMethodSerializer(cards, many=True)
# something like this, although I know this is not right
for card in cards:
if card.id == default_payment_method:
set card.default=True
return Response(cards)
现在的数据看起来像
cards = [
{"id":"pm_1G6u80AFXbZqlwaURe8swF23","billing_details":{"address":{"city":...}}},
{"id":"pm_1G6u80AFXbZqlwaURe8swF23","billing_details":{"address":{"city":...}}}
...
]
但我希望它看起来像:
cards = [
{"id":"pm_1G6u80AFXbZqlwaURe8swF23","default": "True", "billing_details":{"address":{"city":...}}},
{"id":"pm_1G6u80AFXbZqlwaURe8swF23","default": "False", "billing_details":{"address":{"city":...}}}
...
]
你可以做它或序列化器级别。 使用SerializerMethodField
:
class PaymentMethodSerializer(serializers.ModelSerializer):
default = SerializerMethodField()
class Meta:
model = PaymentMethod
def get_default(self, obj):
return obj.id == self.context["default_payment_method"]
注意不要让这个self.context["default_payment_method"]
工作,你应该在你的视图中将default_payment_method
添加到序列化器上下文:
customer = Customer.objects.get(subscriber=request.user.organization_id)
default_payment_method = customer.default_payment_method.organization_id
cards = PaymentMethod.objects.filter(customer=customer.djstripe_id)
serializer = PaymentMethodSerializer(cards, many=True, context={'default_payment_method': default_payment_method})
return Response(serializer.data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.