Search code examples
djangoviewmodelcode-organization

In Django, should a function to reshuffle objects for a specifc view go into the model or the view?


I'm asking for general guidance on what functionality should go into the view code versus the model code.

Specifically, I have a function that takes a list of objects and shuffles them into a list of lists based on whether or not a field has changed. For example:

[{a:1,...},{a:1,...},{a:2,...},{a:1,...},{a:1,...}]

will be transformed into

[[{a:1,...},{a:1,...}],[{a:2,...}],[{a:1,...},{a:1,...}]]

The purpose of this transformation is to prep the data for rendering in a template as nested loops.

Should I create a model function like group_objects(queryset) or should I put this logic into the view? More importantly, what's the thinking behind your recommendation?


Solution

  • If this function is for template rendering it should be a custom template tag (or filter).

    And look at regroup filter, may be it can be used for your task.