Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

django - How to do ModelName.objects.filter in html

I'm trying to eliminate the amount of code I need to put in my view and want to do this in my html file:

{% for committee in c %}
    {% for article in Article.objects.filter(committee=committee) %}
    <a class="post-link" href="{% url 'update' id=article.id %}">{{article.title}}</a>
    {% endfor %}
{% endfor %}

I am passing my article model and list of c as context in my view.

But it gives me this error:

    TemplateSyntaxError at /admin-dash/
Could not parse the remainder: '(committee=committee)' from 'Article.objects.filter(committee=committee)'
Request Method: GET
Request URL:    http://127.0.0.1:8000/admin-dash/
Django Version: 3.1.3
Exception Type: TemplateSyntaxError
Exception Value:    
Could not parse the remainder: '(committee=committee)' from 'Article.objects.filter(committee=committee)'
Exception Location: C:Usersenjaanaconda3libsite-packagesdjangoemplatease.py, line 662, in __init__
Python Executable:  C:Usersenjaanaconda3python.exe
Python Version: 3.8.3
Python Path:    
['C:\Users\benja\Desktop\mysite\mysite',
 'C:\Users\benja\anaconda3\python38.zip',
 'C:\Users\benja\anaconda3\DLLs',
 'C:\Users\benja\anaconda3\lib',
 'C:\Users\benja\anaconda3',
 'C:\Users\benja\anaconda3\lib\site-packages',
 'C:\Users\benja\anaconda3\lib\site-packages\win32',
 'C:\Users\benja\anaconda3\lib\site-packages\win32\lib',
 'C:\Users\benja\anaconda3\lib\site-packages\Pythonwin']
Server time:    Tue, 12 Jan 2021 19:41:28 +0000
Error during template rendering
In template C:UsersenjaDesktopmysitemysitelogemplatesadmin.html, error at line 18

Could not parse the remainder: '(committee=committee)' from 'Article.objects.filter(committee=committee)'
8       <link rel="stylesheet" href="{% static 'css/admin.css' %}">
9       <link rel="stylesheet" href="{% static 'css/posts.css' %}">
10  </head>
11  <main>
12  
13  
14      <div class="admin-panel">
15          <div class="posted">
16              <h1 style='font-size: 7rem; margin-bottom: 20px; margin-top: 0;'>Posts:</h1>
17              {% for committee in c %}
18              {% for article in Article.objects.filter(committee=committee) %}
19              <h1>committee</h1>
20              <a class="post-link" href="{% url 'update' id=article.id %}">{{article.title}}</a>
21              {% endfor %}
22              {% endfor %}
23          </div>
24          <div class="drafts">
25              <h1 style='font-size: 7rem; margin-bottom: 20px;'>Drafts:</h1>
26      
27              <h1>Sustainability Committee:</h1>
28              {% for article in sc1 %}
Traceback Switch to copy-and-paste view
C:Usersenjaanaconda3libsite-packagesdjangocorehandlersexception.py, line 47, in inner
                response = get_response(request) …
? Local vars
C:Usersenjaanaconda3libsite-packagesdjangocorehandlersase.py, line 179, in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) …
? Local vars
C:UsersenjaDesktopmysitemysitelogviews.py, line 89, in admin_view
        return render(request, 'admin.html', context) 

Any idea how to do this? I think it's some sort of syntax. Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You access the related Article objects with:

{% for committee in c %}
    {% for article in committee.article_set.all %}
        …
    {% endfor %}
{% endfor %}

If you use a relation like a ForeignKey, Django will automatically define a relation in reverse, for a ForeignKey, that will be the modelname_set, so in this case article_set. You can change the name of the relation in reverse by specifying the related_name=… parameter [Django-doc].

The above is however not efficient, since it will here make N+1 queries: one query to obtain the Committees, and for each Committee it will make an extra query to obtain the related articles.

In the view, you can use prefetch_related(…) [Django-doc] to fetch the related objects with a single extra query so:

c = Committee.objects.prefetch_related('article_set')

I need to put in my view and want to do this in my html.

Django templates are deliberately restricted not to allow making function calls with parameters. This to avoid writing business logic in the templates, this belongs in the views, not in the templates.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...