简体   繁体   中英

Passing parameter from function to another function in Django

I have these two functions in views.py namely: create_excel and section_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')

I wanted to pass the variable m to another function to filter my excel file.

Here is the 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

How to I get or pass the queryset m from section_landpins to create_excel function for me to filter the excel file result?

It sounds like you want to access the variable between different requests. There are a few ways of doing this:

  1. Just recalculate m when the user visits the second view. If you do this, you should write a separate function that both view methods call, to get m.
  2. If you want to avoid recalculating m in the second view, you could cache the value of m in the first view, and only recalculate it if it expires. https://docs.djangoproject.com/en/dev/topics/cache/
  3. Store the information you need on the session. This is impermanent, as the user's session will expire. https://docs.djangoproject.com/en/dev/topics/http/sessions/

I think I'd go for 1. to begin with and if you experience any performance issues, switch to 2.

Here's an example of how to do 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

you can change the code as

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

I think this will work.

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