在Django中将参数从函数传递给另一个函数

时间:2014-11-20 08:39:46

标签: python django excel

我在views.py中有这两个功能,即:create_excelsection_landpins

section_landpins

def section_landpins(request):
    if request.method == "GET":
        get_id = request.user.id
        pnt = ButuanMaps.objects.get(clandpin='162-03-0001-017-33').geom
        kmdistance = request.GET.get('kmtocity', default=100)
        mysection = request.GET.get('mysection', default='All')
        getarea = request.GET.get('getarea', default=5500000)
        getvalue = request.GET.get('mysoiltype', default=0)
        getvalue1 = request.GET.get('myerosion', default=0)

        args = []
        kwargs = {
            'landproperty__sownerid__id': get_id,
            'geom__distance_lte': (pnt, D(km=kmdistance)),
            'narea__lte': getarea
        }

        if mysection != 'All':
            kwargs['ssectionid__id'] = mysection

        if getvalue != '0':
            args.append(Q(geom__intersects=SoilType.objects.get(id=getvalue).geom))

        if getvalue1 != '0':
            args.append(Q(geom__intersects=ErosionMap.objects.get(id=getvalue1).geom))

        #this queryset below, I want this to be pass to `create_excel` function
        m = ButuanMaps.objects.filter(*args, **kwargs).values_list('clandpin')
        return HttpResponse(json.dumps(list(m)), content_type='application/json')

我想将变量m传递给另一个函数来过滤我的excel文件。

以下是create_excel

def create_excel(request):
    book = xlwt.Workbook(encoding='utf8')
    sheet = book.add_sheet('untitled')

    default_style = xlwt.Style.default_style
    datetime_style = xlwt.easyxf(num_format_str='dd/mm/yyyy hh:mm')
    date_style = xlwt.easyxf(num_format_str='dd/mm/yyyy')

    headers = [f.name for f in SOMEMODELHERE._meta.fields]
    #values should have the query of m from `section_landpins`
    values = LandProperty.objects.all().values_list()
    values_list = [headers] + list(values)

    for row, rowdata in enumerate(values_list):
        for col, val in enumerate(rowdata):
            if isinstance(val, datetime):
                style = datetime_style
            elif isinstance(val, date):
                style = date_style
            else:
                style = default_style
            sheet.write(row, col, val, style=style)

    response = HttpResponse(mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=example.xls'
    book.save(response)
    return response

如何将查询集msection_landpins传递到create_excel函数,以便我过滤excel文件结果?

2 个答案:

答案 0 :(得分:1)

听起来您想要在不同请求之间访问变量。有几种方法可以做到这一点:

  1. 只需在用户访问第二个视图时重新计算m。如果你这样做,你应该写一个单独的函数,两个视图方法调用,以获得m。
  2. 如果要避免在第二个视图中重新计算m,可以在第一个视图中缓存m的值,并且只有在它到期时才重新计算。 https://docs.djangoproject.com/en/dev/topics/cache/
  3. 在会话中存储您需要的信息。这是无常的,因为用户的会话将过期。 https://docs.djangoproject.com/en/dev/topics/http/sessions/
  4. 我想我会先选择1.如果遇到任何性能问题,请切换到2.

    以下是如何做1:。

    的示例
    def section_landpins(request):
        queryset = get_landpins_from_request(request)
        return HttpResponse(json.dumps(list(queryset)), content_type='application/json')
    
    def create_excel(request):
        queryset = get_landpins_from_request(request)
        # Do rest of processing here
        return response
    
    def get_landpins_from_request(request):
        "Returns queryset of landpins based on GET request."
        # Add processing of request.GET into a queryset here
        return queryset
    

答案 1 :(得分:0)

您可以将代码更改为

def section_landpins(request):
  if request.method == "GET":
    get_id = request.user.id
    pnt = ButuanMaps.objects.get(clandpin='162-03-0001-017-33').geom
    kmdistance = request.GET.get('kmtocity', default=100)
    mysection = request.GET.get('mysection', default='All')
    getarea = request.GET.get('getarea', default=5500000)
    getvalue = request.GET.get('mysoiltype', default=0)
    getvalue1 = request.GET.get('myerosion', default=0)

    args = []
    kwargs = {
        'landproperty__sownerid__id': get_id,
        'geom__distance_lte': (pnt, D(km=kmdistance)),
        'narea__lte': getarea
    }

    if mysection != 'All':
        kwargs['ssectionid__id'] = mysection

    if getvalue != '0':
        args.append(Q(geom__intersects=SoilType.objects.get(id=getvalue).geom))

    if getvalue1 != '0':
        args.append(Q(geom__intersects=ErosionMap.objects.get(id=getvalue1).geom))

    #this queryset below, I want this to be pass to `create_excel` function
    request.m = ButuanMaps.objects.filter(*args, **kwargs).values_list('clandpin')
    return create_excel(request)



 def create_excel(request):
    book = xlwt.Workbook(encoding='utf8')
    sheet = book.add_sheet('untitled')

    default_style = xlwt.Style.default_style
    datetime_style = xlwt.easyxf(num_format_str='dd/mm/yyyy hh:mm')
    date_style = xlwt.easyxf(num_format_str='dd/mm/yyyy')

    headers = [f.name for f in SOMEMODELHERE._meta.fields]
    #the required queryset can be accessed this way
    values = request.m
    values = LandProperty.objects.all().values_list()
    values_list = [headers] + list(values)

    for row, rowdata in enumerate(values_list):
       for col, val in enumerate(rowdata):
           if isinstance(val, datetime):
               style = datetime_style
           elif isinstance(val, date):
               style = date_style
           else:
               style = default_style
           sheet.write(row, col, val, style=style)

    response = HttpResponse(mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=example.xls'
    book.save(response)
    return response

我认为这会奏效。