我很难理解如何最好地构建我的观点。我正在提取各种用户的数据并创建汇总其中一些变量的变量(例如每周发生的事件等)。这样我就可以在模板中绘制这些摘要变量。我正在做很多不同的操作,这些操作变得非常混乱,我需要对其他模板进行这些操作。在这种情况下,有人可以建议如何最好地构建视图。我认为使用类是为其他模板使用相同函数的解决方案,但我不太明白如何。我也觉得必须有一种更好的方法来构建数据库数据的每个操作。
def dashboard(request):
posts= Post.objects.filter(user=request.user)
posts_count = posts.count()
post_early = Post.objects.filter(user=request.user).earliest('date') #need to extract the date value from this so I can take the difference
total_days = (datetime.datetime.now().date()- post_early.date).days
average_30days= round((posts_count/total_days)*30,2)
list4=[]
list5=[]
i=1
time3=datetime.datetime.now() + datetime.timedelta(-30)
while i<32:
list4.append(days2(time3,request,Post))
list5.append(time3.strftime('%b %d, %Y'))
i+=1
time3=time3 + datetime.timedelta(+1)
def dashboardView(request):
posts = Post.objects.filter(user=request.user)
posts_count = posts.count()
#need to extract the date value from post_early so I can take the difference
post_early = Post.objects.filter(user=request.user).earliest('date')
total_days = (datetime.datetime.now().date() - post_early.date).days
average_30days = round((posts_count/total_days)*30,2)
list_4 = []
list_5 = []
i = 1
time_3=datetime.datetime.now() + datetime.timedelta(-30)
while i<32:
list_4.append(days2(time_3, request, Post))
list_5.append(time_3.strftime('%b %d, %Y'))
i += 1
time_3 = time_3 + datetime.timedelta(1)
我会做这样的事情。有一些不一致:
- 保持运算符之前的空格和运算符之后的空格(=,*, - ,+,...)。
- 我会考虑一个好的做法,总是后缀 - 查看你的观点,但这只是个人喜好
- 使用空行分隔代码块,而不是变量组。如果您有一长串变量声明(不是这种情况),您可以使用注释来分隔和分类它们。
- 使用list_3而不是list3(和类似情况),它更具可读性。
有关更多内容,您可以随时查看官方python样式指南:https://www.python.org/dev/peps/pep-0008/
无论如何,如果你在学习的过程中保持一致并达到Django文档中使用的编码风格,你会没事的。
##### EDIT:注意:我的答案是基于您提供的代码,它似乎被剪切(没有返回语句?)而没有其他模块。
您正在使用基于函数的视图,这种视图没有错也不正确,只是其中一种可能的选择。如果你不喜欢它,或者想尝试别的东西,ListView可能适合你:https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-display/
例:
from django.views import ListView
class DashboardView(ListView):
model = Post
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['posts'] = Post.objects.filter(user=request.user)
# add all the data you need to the context dictionary
return context