How it works...

The {% load_objects %} template tag loads a QuerySet defined by the method of the manager from a specified app and model, limits the result to the specified count, and saves the result to the given context variable.

The following code is a simple example of how to use the template tag that we have just created. It will load all news articles in any template, using the following snippet:

{% load utility_tags %}
{% load_objects all from news.Article as all_articles %}
<ul>
{% for article in all_articles %}
<li><a href="{{ article.get_url_path }}">
{{ article.title }}</a></li>
{% endfor %}
</ul>

This is using the all() method of the default objects manager of the Article model, and it will sort the articles by the ordering attribute defined in the Meta class of the model.

Next is an example that uses a custom manager with a custom method to query the objects from the database. A manager is an interface that provides the database query operations to models.

Each model has at least one manager called objects, by default. For our Article model, we added an extra manager called custom_manager with a method, random_published(). Here is how we can use it with our {% load_objects %} template tag to load one random published article:

{% load utility_tags %}
{% load_objects custom_manager.random_published from news.Article limit 1 as random_published_articles %}
<ul>
{% for article in random_published_articles %}
<li><a href="{{ article.get_url_path }}">
{{ article.title }}</a></li>
{% endfor %}
</ul>

Let's look at the code of the {% load_objects %} template tag. In the parsing function, there are two allowed forms for the tag—with or without a limit. The string is parsed, and if the format is recognized, the components of the template tag are passed to the ObjectsNode class.

In the render() method of the Node class, we check the manager's name and its method's name. If no manager is specified, _default_manager will be used. This is an automatic property of any model injected by Django and points to the first available models.Manager() instance. In most cases, _default_manager will be the objects manager. After that, we will call the method of the manager and fall back to an empty QuerySet if the method doesn't exist. If a limit is defined, we resolve the value of it and limit the QuerySet accordingly. Lastly, we will store the resulting QuerySet in the context variable, as given by var_name.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.78.106