gpt4 book ai didi

python - 将值附加到序列化器数据

转载 作者:行者123 更新时间:2023-12-01 06:28:40 25 4
gpt4 key购买 nike

我正在从 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 添加到序列化器 context在您看来:

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)

关于python - 将值附加到序列化器数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60008876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com