django 传递参数的方式

1、view和url传递参数

            参数方式一: url.py
            path('xxx/', MailTemplateList.as_view(), name='MailTemplateList'),
            path('xxx/<str:id>/', MailTemplateList.as_view(), name='MailTemplateList'),
            说明: http://xxx/id 这个id可以在 get(self,request,id=none) 方法中,用实参数获取,必须同名,也叫id

            参数方式二:html的href
               <a href="xxx/?{%p_code=130000%}">{{ 河北省  }}
             p_code = kwargs.get('p_code')
             #如上,p_code的获取方法是kwargs字典

2、Form传递参数

#(1)view中调用Form
formset = KhPersonResultFormSet(username=request.user.username, period_id=self.kwargs.get('period_id'))

#(2)form的init中,提取参数,进行动态初始化
class KhPersonResultFormSet(RecordBase):
    def __init__(self, *args, **kwargs):
        self.username = kwargs.pop('username')
        self.period_id = kwargs.pop('period_id')
        super().__init__(*args, **kwargs)
        # myuser = get_object_or_404(User, username=self.username)
        self.queryset = KhPersonResult.objects.filter(zhukao_user=self.username, kaohe_period=self.period_id).order_by('beikao_user__user_type','beikao_user__jg__id','beikao_user__p_bh')

 

3、字典参数 的pop和get

def my_func(a, b, **kwargs):
    c = kwargs.get("c", 0)
    return a + b + c


#在model中,custom save参数,添加保存的字段
# blog/models.py
def save(self, **kwargs):
    self.updated_date = datetime.now()
    super().save(**kwargs)

 

调用第三方api的改善:The long way:

def get_orders(api, a = None, b = None, c = None, d = None, e = None, f = None, g = None):
    return api.get(a=a, b=b, c=c, d=d, e=e, f=f, g=g)

The short way:

def get_orders(api, **kwargs):
    return api.get(**kwargs)

dict.get, dict.pop的唯一区别是:pop后,字典里就剔除了,get可以多次数据不变
def multiply_numbers(**kwargs):
    x = kwargs.get('x',0)
    y = kwargs.get('y',0)
    return x * y
print(multiply_numbers(x=5,y=6)) # Output: 30


def add_numbers(**kwargs):
    x = kwargs.pop('x',0)
    y = kwargs.pop('y',0)
    return x + y
print(add_numbers(x=5,y=6)) # Output: 11

 

posted @ 2023-07-12 09:47  花生与酒  阅读(935)  评论(0编辑  收藏  举报