如何构造视图以进行数据库拉取和操作

时间:2019-03-26 17:32:05

标签: django django-views django-database

我在理解如何最好地组织观点方面遇到困难。 我正在收集各种用户的数据,并创建汇总了其中一些变量的变量(例如每周发生的次数等)。因此,我可以在模板中绘制这些摘要变量。我正在做很多不同的操作,这些操作变得非常混乱,对于其他模板,我将需要这些操作。在这种情况下,有人可以推荐如何最好地构造视图。我认为使用类是对其他模板使用相同功能的解决方案,但我不太了解如何使用。我还觉得必须有一种更好的方法来构造数据库数据的每种操作。

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)

1 个答案:

答案 0 :(得分:0)

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文档中使用的编码风格,那就可以了。

#####编辑:

注意:我的答案是基于您提供的代码的,它似乎被剪切(没有return语句?),并且没有其他模块。

您使用的是基于函数的视图,该视图既不正确也不正确,只是可能的选择之一。如果您不喜欢它,或者想尝试其他方法,可以使用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