Break nested loop in Django views.py with a function
I have a nested loop that I would like to break out of. After searching this site it开发者_运维百科 seems the best practice is to put the nested loop into a function and use return to break out of it. Is it acceptable to have functions inside the views.py file that are not a view? What is the best practice for the location of this function? Here's the example code from inside my views.py
@login_required
def save_bookmark(request):
if request.method == 'POST':
form = BookmarkSaveForm(request.POST)
if form.is_valid():
bookmark_list = Bookmark.objects.all()
for bookmark in bookmark_list:
for link in bookmark.link_set.all():
if link.url == form.cleaned_data['url']:
# Do something.
break
else:
# Do something else.
else:
form = BookmarkSaveForm()
return render_to_response('save_bookmark_form.html', {'form': form})
You shouldn't think of Django views as being in any way special. It's just Python. As such, you can have whatever functions you like in views.py. The only limitation is that views themselves have to take a request object and return a subclass of HttpResponse
. Other than that, you can do what you like in that module, including having functions, classes or constants that are used by your views.
If you have a lot of utility functions, you may want to consider extracting them into eg a lib.py
in your app directory for the sake of tidiness. But there's no need to do that if you've just got one or two.
Yes. it's fine to have functions in views.py
that are not views - (I do this all the time). This is particularly appropriate if the function is only for use within that module (i.e. by views in that views.py
), or by just a single view function.
You could always make it a private function if you're worried about exposing it to the outside world. Also, try avoid giving it a parameter called request
, I tend to subconsciously parse functions which take a request as view functions when reading code.
精彩评论