Jarad
Jarad

Reputation: 18893

Should Django Querysets Be Called in the Templates or Passed Into The Template Context?

I may get blowback from asking this question but it's something I've wondered about for a while so here goes.

In a Django template, you can use .all to get the queryset of things, like so:

{% for prerequisite in object.prerequisites.all %}
  <li class="list-group-item">{{ prerequisite.text }}</li>
{% endfor %}

The model in this case looks like this, but the only relevant piece of information is that object above has a relation to the Prerequisite model through the ForeignKey.

class Prerequisite(models.Model):
    content = models.ForeignKey(Content, on_delete=models.CASCADE,
                                related_name='prerequisites')
    text = models.CharField(max_length=100)

    def __str__(self):
        return str(self.text)

My question is

Is it best-practice to call Django querysets in the template, (ie: object.prerequisites.all) or should one pass it in the view through the context?

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['prerequisites'] = self.object.prerequisites.all()
    return context

It's really convenient to do querysets in the template, but it seems like it should be business logic located in the view. Does Django have a specific stance on this?

Upvotes: 0

Views: 55

Answers (1)

oruchkin
oruchkin

Reputation: 1295

according to django documentation:

The view layer - Django has the concept of “views” to encapsulate the logic responsible for processing a user’s request and for returning the response.

The template layer - The template layer provides a designer-friendly syntax for rendering the information to be presented to the user.

i have different example, i know a lot of programmers loves to move buisness logic from views.py to serializer.py, even if original purpose of serialezers life is - to serialize

i believe the most appropriate way is to pass your data through context in the views.

Views originally is all your buisness logic, serializer suppose only serialization, and templates purpose is to show html page, python wasn't originaly desined to manipulate html page

Upvotes: 1

Related Questions