Home > Net >  Using **kwargs, a dictionary from views was not successfully pass to a function in models properly
Using **kwargs, a dictionary from views was not successfully pass to a function in models properly

Time:11-26

I am trying to pass a dictionary in views to a function in models and using **kwargs to further manipulate what i want to do inside the function. I try to call the dict before passing it in to the function. The data is there. The moment the dict was pass to the function (isAvailable) the kwargs is empty.

Here are the code snippets from views.py.

def bookingAvailable(request):
    available = isAvailable(data=request.data)

Here are the code snippets from models.py

def isAvailable(**kwargs):
    bookedDate = kwargs.get('bookedDate')
    customerID = kwargs.get('customerID')
    cpID = kwargs.get('cpID')

request.data is populated with data in a dictionary form. But the moment it got in to **kwargs everything is gone. Not so sure what happen in between. Any help is appreciated!

CodePudding user response:

When you do isAvailable(data=request.data), kwargs will be assigned a dictionary that looks like

{
    "data": ...
}

Notice there is no key "bookedDate" or "customerID" because you explictly specified data=... in the call.

I assume that bookedData and customerID are keys in request.data. To pass these keys as key word arguments, use the ** operator:

isAvailable(**request.data) 

In addition to this change, you can declare the parameters explicitly:

def isAvaialble(bookedDate, customerId, cpId):
    pass

Notice how much less code this is than calling kwargs.get() for each parameter.

CodePudding user response:

You should get first data dictionary from kwargs and then get fields from data dictionary:

def isAvailable(**kwargs):
  data = kwargs.get('data')
  bookedDate = data.get('bookedDate')
  customerID = data.get('customerID')
  cpID = data.get('cpID')
  • Related