简体   繁体   中英

Django: Passing **kwargs

I have a question regarding passing **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 . For each def I am passing currently the kwargs. However, I hoped to find a way that I only have to write it once in views.py . And then I can just use **kwargs to collect the data and pass them. 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)

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

2) models.py :

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

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 :

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

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:

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) . You've got to fetch it from kwargs :

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

I'm not sure I'd encourage you to use **kwargs like this. When I see the method def charge(self, order_id, total, token): it's immediately clear how to call it. def charge(self, **kwargs) is less clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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