Django:数据库条目两次
我在Django项目中使用Stripe,首先向客户收费。在我获得var费用后,我在我的Django:数据库条目两次,django,stripe-payments,Django,Stripe Payments,我在Django项目中使用Stripe,首先向客户收费。在我获得var费用后,我在我的费用模型中输入该数据,并在我的费用模型中保存数据。现在我意识到,一旦保存外键:charge=new\u charge\u obj,整个POST请求将运行两次。我为我的费用型号分配外键(费用)的方法是否错误 if request.method == 'POST': stripe.api_key = "XYZ" # TODO Marc (it said keep api in call?)
费用
模型中输入该数据,并在我的费用
模型中保存数据。现在我意识到,一旦保存外键:charge=new\u charge\u obj
,整个POST请求将运行两次。我为我的费用
型号分配外键(费用
)的方法是否错误
if request.method == 'POST':
stripe.api_key = "XYZ" # TODO Marc (it said keep api in call?)
token = request.POST.get('stripeToken')
# atomic ?
#try:
charge = stripe.Charge.create(
amount=900,
application_fee=100,
currency='EUR', # TODO Marc
source=token,
stripe_account="XYZ", # TODO Marc: Replace with organizer stripe account
)
new_charge_obj = Charge.objects.create(
amount=charge.amount,
# amount_refunded=charge.amount_refunded,
charge_id=charge.id,
livemode=charge.livemode,
paid=charge.paid,
refunded=charge.refunded,
currency=charge.currency,
failure_code=charge.failure_code,
failure_message=charge.failure_message,
fraud_details=charge.fraud_details,
outcome=charge.outcome,
status=charge.status,
application_fee=charge.application_fee,
captured=charge.captured,
created=charge.created,
)
application_fee = stripe.ApplicationFee.retrieve(charge.application_fee)
Fee.objects.create(
fee_id=application_fee.id,
livemode=application_fee.livemode,
currency=application_fee.currency,
amount=application_fee.amount,
charge=new_charge_obj,
)
您可以使用
get\u或\u create()
来防止创建重复项
charge = stripe.Charge.get_or_create(
amount = 900,
application_fee = 100,
currency = 'EUR', #TODO Marc source = token,
stripe_account = "XYZ", #TODO Marc: Replace with organizer stripe account
)
new_charge_obj = Charge.objects.get_or_create(
amount = charge.amount, #amount_refunded = charge.amount_refunded,
charge_id = charge.id,
livemode = charge.livemode,
paid = charge.paid,
refunded = charge.refunded,
currency = charge.currency,
failure_code = charge.failure_code,
failure_message = charge.failure_message,
fraud_details = charge.fraud_details,
outcome = charge.outcome,
status = charge.status,
application_fee = charge.application_fee,
captured = charge.captured,
created = charge.created,
)
application_fee = stripe.ApplicationFee.retrieve(charge.application_fee)
Fee.objects.get_or_create(
fee_id = application_fee.id,
livemode = application_fee.livemode,
currency = application_fee.currency,
amount = application_fee.amount,
charge = new_charge_obj,
)