📜 ⬆️ ⬇️

Different display options for the same data.

The experience of "fun" is becoming more and more. Here is another case of insanity. Short essence:
There is a site where you need to display the same objects with different sampling conditions (by category, by tag, “zahabarenye”, etc.) and different displays (list, detail, etc.).

Some individuals create an intricate structure of if-s in each view, and each time it repeats. Remember:
  1. Refactoring
  2. Refactoring
  3. Refactoring
  4. view is just a function!

And so, on the last point. Many do not understand that view is just a function that returns HttpResponse and no more, therefore, it is much more intelligent to distinguish actions specific to a particular display, and indeed the choice of displaying into a separate function. This is easily done by calling at the end of the main view:
  return extra_view (request, objects = myobjects) 

For completeness of perception, I will give the code in more.
 def list (request):
     "" "
     Displays a list of all objects.
     "" "
     myset = MyDataObject.objects.all ()
     return extra_view (request, myset)
 def category (request, category_id):
     "" "
     Lists objects by category
     "" "
     category = get_object_or_404 (Category, pk = category_id)
     myset = MyDataObject.objects.filter (category = category)
     return extra_view (request, myset)
 def extra_view (request, object_set):
     "" "
     Wrapper
     "" "
     view_type = request.GET.get ('view_type', 'list')
     return render_to_response ('view_type /% s.html'% view_type ', {' objects': object_set}

This is an extremely simple example (sorry, a little lazy to write more, but I can’t show the working code, for obvious reasons). I have still hung: sorting, selection by date, etc.
I note that you can easily use decorators, and then everything will change a little, but these are trifles (instead of returning extra_view, the function will return just object_set; I just understand the presented approach)

PS> Remember the effectiveness and beauty of the code, it is extremely important.
PPS> Of course, this article is more about refactoring and MVC, but I encounter this error most often in django projects, I don’t know why.

')

Source: https://habr.com/ru/post/28084/


All Articles