[英]Append values to serializer data
I am fetching some customer credit cards from an API.我正在从 API 获取一些客户信用卡。 The data does not indicate the customers 'default' card, although another API can do this.
数据并不表示客户的“默认”卡,尽管另一个 API 可以做到这一点。 I would like to filter over the first data set and add a value indicating if the card matches the default card.
我想过滤第一个数据集并添加一个值,指示该卡是否与默认卡匹配。
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)
Right now the data looks like现在的数据看起来像
cards = [
{"id":"pm_1G6u80AFXbZqlwaURe8swF23","billing_details":{"address":{"city":...}}},
{"id":"pm_1G6u80AFXbZqlwaURe8swF23","billing_details":{"address":{"city":...}}}
...
]
But I would like it to look like:但我希望它看起来像:
cards = [
{"id":"pm_1G6u80AFXbZqlwaURe8swF23","default": "True", "billing_details":{"address":{"city":...}}},
{"id":"pm_1G6u80AFXbZqlwaURe8swF23","default": "False", "billing_details":{"address":{"city":...}}}
...
]
You can do it or serializer level.你可以做它或序列化器级别。 Use
SerializerMethodField
:使用
SerializerMethodField
:
class PaymentMethodSerializer(serializers.ModelSerializer):
default = SerializerMethodField()
class Meta:
model = PaymentMethod
def get_default(self, obj):
return obj.id == self.context["default_payment_method"]
Note than to make this self.context["default_payment_method"]
work you should add default_payment_method
to serializer context in your view:注意不要让这个
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.