django - Django,如何在另一个视图中重用变量结果?
问题描述
我有以下问题要问你。我想知道在另一个视图中重用在视图中获得的一些可变结果的最佳和优雅的方法。
我试图用一个例子更好地解释我。
我有 2 个不同的应用程序,应用程序A
和应用程序B
。
在 app A
views.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)
我已经用上面的解决方案解决了。
解决方案
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 中使用。你可以尝试类似的东西
推荐阅读
- r - R中的随机参数负二项式模型
- laravel - Laravel 登录/注册后重定向到预期页面
- javascript - 使用 javascript 类方法重置先前提交的表单的值
- javascript - 调用 getElementsByTagName 后更改 innerHTML
- virtualbox - 如何下载适用于 Windows 10 的虚拟机的快速入门 VM 5.x?
- php - PHP数组合并,忽略某些重复的键,让它们包含在内部创建的数组中
- git - git push 不断在提交中添加奇怪的用户名@IP 地址
- android - 在 Android Kotlin 中与使用 Knockout.js 构建的网站进行交互
- c++ - 访问检查如何在类型别名模板中工作?
- java - 如何在java中使用AWS Textract检索pdf中存在的表