简体   繁体   English

使用 **kwargs,视图中的字典未成功传递给模型中的 function

[英]Using **kwargs, a dictionary from views was not successfully pass to a function in models properly

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.我正在尝试将视图中的字典传递给模型中的 function,并使用 **kwargs 进一步操纵我想要在 function 中执行的操作。 I try to call the dict before passing it in to the function.我尝试在将字典传递给 function 之前调用它。 The data is there.数据在那里。 The moment the dict was pass to the function (isAvailable) the kwargs is empty.将 dict 传递给 function (isAvailable) 的那一刻,kwargs 是空的。

Here are the code snippets from views.py.以下是 views.py 中的代码片段。

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

Here are the code snippets from models.py以下是来自 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. request.data 以字典形式填充数据。 But the moment it got in to **kwargs everything is gone.但是当它进入 **kwargs 的那一刻,一切都消失了。 Not so sure what happen in between.不太清楚中间会发生什么。 Any help is appreciated!任何帮助表示赞赏!

When you do isAvailable(data=request.data) , kwargs will be assigned a dictionary that looks like当您执行isAvailable(data=request.data)时,将为kwargs分配一个看起来像

{
    "data": ...
}

Notice there is no key "bookedDate" or "customerID" because you explictly specified data=... in the call.请注意,没有键"bookedDate""customerID" ,因为您在调用中明确指定了data=...

I assume that bookedData and customerID are keys in request.data .我假设bookedDatacustomerIDrequest.data中的键。 To pass these keys as key word arguments, use the ** operator:要将这些键作为关键字 arguments 传递,请使用**运算符:

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.请注意,这比为每个参数调用kwargs.get()少了多少代码。

You should get first data dictionary from kwargs and then get fields from data dictionary:您应该从 kwargs 获取第一个数据字典,然后从数据字典中获取字段:

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

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

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