Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template: How to use values/values_list

In template I am trying to do something like this:

{{ request.user.profile.following.all.values_list }}

and I get

<QuerySet [(7, 2, 1)]>

, but I want to get

<QuerySet [2]>

like in Django values_list. For example: Follow.objects.filter(follow_by=self.request.user.profile).values_list('follow_to', flat=True) Can I pass argument like this in template?

like image 794
bkrop Avatar asked Dec 10 '25 06:12

bkrop


1 Answers

Can I pass argument like this in template?

No. The Django template engine deliberately restricts this, since this is logic that belongs in the view. For example:

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    following = request.user.profile.following.values_list('follow_to', flat=True)
    return render(
        request,
        'some_template.html',
        {'following': following}
    )

You can then render this with:

{{ following }}

That being said, using .values_list(…) [Django-doc] is often an anti-pattern, since it erodes the model layer. It is thus something related to the primitive obsession antipattern [refactoring.guru].

like image 178
Willem Van Onsem Avatar answered Dec 14 '25 03:12

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!