jhon arab
jhon arab

Reputation: 81

Get queryset by using filter objects on template in django

In models:

class Match(models.Model):
    hot_league = models.ManyToManyField(HotLeague, blank=True)

class HotLeague(models.Model):
    user = models.ManyToManyField(User, blank=True)
    price_pool = models.IntegerField()
    winner = models.IntegerField()

In Views:

match = get_object_or_404(Match, pk=pk)

Here i need to access this Match queryset.

that's why

In template:

{% for hot_league in match.hot_league.all %}

By writing match.hot_league.all in template I can get all queryset of HotLeague class. But I want to use filter here with user. Like in views we can use HotLeague.objects.filter(user=request.user). But {% for hot_league in match.hot_league.filter(user=request.user) %} is not working on template.

How can I do that kind of filter in template?

Upvotes: 0

Views: 216

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

How can I do that kind of filter in template?

Templates are deliberately restricted to avoid that. Some template processors, like Jinja can make function calls, but usually if you have to do that, something is wrong with the design. Views should determine what to render, and templates should render that content in a nice format.

In your view, you thus can render this as:

def some_view(request, pk):
    match = get_object_or_404(Match, pk=pk)
    hot_leagues = match.hot_league.filter(user=request.user)
    return render(
        request,
        'some_template.html',
        {'match': match, 'hot_leagues': hot_leagues}
    )

In your template, you can then render this like:

{% for hot_league in hot_leagues %}
    <!-- -->
{% endfor %}

Upvotes: 1

Related Questions