首页 > 解决方案 > Django,如何在另一个视图中重用变量结果?

问题描述

我有以下问题要问你。我想知道在另一个视图中重用在视图中获得的一些可变结果的最佳和优雅的方法。

我试图用一个例子更好地解释我。

我有 2 个不同的应用程序,应用程序A和应用程序B

在 app Aviews.py 中,我有很多代码来处理模型中的数据,并创建了很多新变量。现在,在 app 中,B我有必要重用在 views.py app 中获得的一些变量A,但我不会再次编写相同的代码来获取它们。

有没有办法实现我的目标?

编辑

按照@sandeshdaundkar 的建议,我可以克服创建新函数并在每个应用程序的views.py 中调用它的问题。

我试图达到这个结果,但我不擅长 python 的功能以及如何在我的views.py 中调用它。

我在 my_app/utility.py 中创建了以下函数:

def my_func():

    defaults = list(0 for m in range(13))
    iva_debito = dict()
    for year, month, totale in(Ricavi.objects.values_list( 'data_contabile__year', 'data_contabile__month').
        annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('ricavo')*(F('iva'))),
        output_field=FloatField())).values_list('data_contabile__year', 'data_contabile__month', 'totale')):
        if id not in iva_debito.keys():
            iva_debito[id]=list(defaults)
        index=month
        iva_debito[id][index]=totale

    iva_debito_totale={'IVA a Debito Totale': [sum(t) for t in zip(*iva_debito.values())],}

    context= {
        'iva_debito_totale':iva_debito_totale,
    }

    return context

这里是我的 my_app/views.py: ... from .utility import my_func

def iva(request):
    data = my_func()
    iva_debito_totale=data['iva_debito_totale']

    context= {
        'iva_debito_totale': iva_debito_totale,
    }

    return render(request, 'iva/iva.html', context)

我已经用上面的解决方案解决了。

标签: djangodjango-modelsdjango-rest-frameworkdjango-formsdjango-views

解决方案


def func_name():
        # do calculation,
        return context_for_view_one, obj_to_reuse

def view_one(request):
    context, iva = func_name()
    return render(context=context) # context to be used in view a

def view_two(request):
    context, iva = func_name()
    return render(context=iva) # iva to be used in view b
def iva(request):
    data = func_name()
    iva_debito_totale = data['iva_debito_totale']
    return render(request, 'template.html', context={'totale': iva_debito_totale})

我希望这能给你一个想法,我们从公共函数返回 2 个对象。一个将在 view_one 中使用,其他将在 view_two 中使用。你可以尝试类似的东西


推荐阅读