简体   繁体   English

Django:传递** kwargs

[英]Django: Passing **kwargs

I have a question regarding passing **kwargs . 我有一个关于传递**kwargs的问题。 In views.py I am collecting data such as order_id etc. This data I am passing to the charge function from where I call the ChargeManager . views.py我正在收集诸如order_id等数据。此数据正从我称为ChargeManager地方传递到收费功能。 For each def I am passing currently the kwargs. 对于每场def我目前都在传递小矮人。 However, I hoped to find a way that I only have to write it once in views.py . 但是,我希望找到一种方法,只需在views.py编写一次即可。 And then I can just use **kwargs to collect the data and pass them. 然后我可以使用**kwargs收集数据并传递它们。 However whatever I am trying I am struggling to get it working. 但是,无论我在尝试什么,我都在努力使其正常运行。 Do you have any ideas why? 你有什么想法吗?

Example how I wanted it to work: 我希望它如何工作的示例:

1) 1)

paid = instance.charge(order_id=session_order_id, total=total, token=token)

2) models.py : 2) models.py

TransactionProfile
    def charge(self, **kwargs):
        return Charge.objects.stripe_charge(self, order_id, total, token)

3) models.py : 3) models.py

ChargeManager
    def stripe_charge(self, **kwargs): 
        print(order_id)

Currently, I have to do it this way: 目前,我必须这样做:

views.py

paid = instance.charge(order_id=session_order_id, total=total, token=token)

models.py

def charge(self, order_id, total, token):
    return Charge.objects.stripe_charge(self, order_id, total, token)

models.py : models.py

TransactionProfile
    def charge(self, order_id, total, token):
        return Charge.objects.stripe_charge(self, order_id, total, token)

models.py : models.py

ChargeManager
    def stripe_charge(self, transaction_profile, order_id, total, token):

If your function accepts kwargs you can call another method with the same kwargs: 如果您的函数接受kwargs,则可以使用相同的kwargs调用另一个方法:

def charge(self, **kwargs):
    return Charge.objects.stripe_charge(self, transaction_profile=self, **kwargs)

If your stripe_charge method only accepts kwargs , you can no longer use print(order_id) . 如果您的stripe_charge方法仅接受kwargs ,则不能再使用print(order_id) You've got to fetch it from kwargs : 您必须从kwargs获取它:

def stripe_charge(self, **kwargs): 
    print(kwargs['order_id'])

I'm not sure I'd encourage you to use **kwargs like this. 我不确定是否会鼓励您使用像这样的**kwargs When I see the method def charge(self, order_id, total, token): it's immediately clear how to call it. 当我看到方法def charge(self, order_id, total, token):立即清楚如何调用它。 def charge(self, **kwargs) is less clear. def charge(self, **kwargs)不太清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM