我在django中有一个视图,它有一个使用两个日期的过滤器。我想在一个单独的函数中计算日期以稍微整理一下并将它们返回到视图中。
def index(request):
function = month()
objectcount = Entry.objects.filter(entrydate__range=(function[0], function[1])).count() #bleurgh!
context = {
"objectcount": objectcount,
}
return render(request, 'entry/index.html', context)
def month():
today = datetime.datetime.now().date()
first_of_month = "{}-{}-01".format(today.year, today.month)
last = calendar.monthrange(today.year, today.month)[1]
last_of_month = "{}-{}-{}".format(today.year, today.month, last)
return first_of_month, last_of_month
这很好用,但我必须使用function[0]
和function[1]
来访问变量。
如何传递这些变量,以便使用名称从索引视图访问它们,例如first_of_month
和last_of_month
?
答案 0 :(得分:1)
也许你这样写
def month():
today = datetime.datetime.now().date()
first_of_month = "{}-{}-01".format(today.year, today.month)
last = calendar.monthrange(today.year, today.month)[1]
last_of_month = "{}-{}-{}".format(today.year, today.month, last)
resp_data ={"first_of_month":first_of_month,"last_of_month":last_of_month}
return resp_data
function["first_of_month"]
function["last_of_month"]
答案 1 :(得分:1)
将它们作为元组传递
return (first_of_month, last_of_month)
并通过索引访问它。
将它们作为字典传递给
var ={"a":a,"b":b}
return var