简体   繁体   English

三串代码在三个不同的视图函数中重复

[英]Three strings of code repeat in three different view-functios

I have three view-functions in views.py in django project that using a same three arguments in them:我在 django 项目的 views.py 中有三个视图函数,它们使用相同的三个参数:

paginator = Paginator(post_list, settings.POSTS_LIMIT)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)

How can I put em in a single function (make an utility) to use one string of code in my view-functions, instead of repeat using three?如何将 em 放在一个函数中(创建一个实用程序)以在我的视图函数中使用一串代码,而不是重复使用三个? Thats my first question here, thank you :)这是我的第一个问题,谢谢:)

As you note, you can create a single function to handle this, taking the info it needs as arguments.正如您所注意到的,您可以创建一个函数来处理这个问题,将它需要的信息作为参数。 You can include this as a helper function in your views.py or separate it out into a utils.py and then import it.您可以将其作为辅助函数包含在您的 views.py 中,或者将其分离到 utils.py 中,然后将其导入。 Assuming the latter, for tidiness and future-proofing假设是后者,为了整洁和面向未来

utils.py实用程序.py

from django.core.paginator import Paginator
from django.conf.settings import POSTS_LIMITS #you may have another place for your settings
from .utils import make_pagination #utils.py file in same directory

def make_pagination(request, thing_to_paginate, num_per_page=POSTS_LIMITS)
    paginator = Paginator(thing_to_paginate, num_per_page)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return page_obj

views.py视图.py

from .utils import make_pagination

def records(request):
   ...
   #we'll use the provided settings-based default for num_per_page
   page_obj = make_pagination(request, post_list)
   return render(request, 'template.html', {'page_obj': page_obj})

If you wanted more than just the page_obj for some reason, you can return more than the one value, eg,如果出于某种原因您想要的不仅仅是 page_obj,您可以返回多个值,例如,

utils.py实用程序.py

...
return page_obj, paginator

views py视图 py

...
page_obj, paginator = make_pagination(request, post_list)

I've gotten the page number in the function itself, but you can also do that either in the view itself, or even in the function call in the view eg,我已经在函数本身中获得了页码,但您也可以在视图本身中执行此操作,甚至在视图中的函数调用中执行此操作,例如,

make_pagination(request.GET.get('page') or 1, post_list)

(If you go this path, don't forget to change the function to accommodate the different argument) (如果你走这条路,别忘了改变函数来适应不同的参数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM