简体   繁体   中英

context and dictionaries python Django

So I have the following code:

views.py:

def topics(request):
    """Show all topics"""
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)
        return render(request, 'learning_logs/topic.html', context)

I understand that I am querying the database and sorting the data by date then storing that data in the topics variable. My first question is, is the topics variable storing the data as a list? (assuming multiple entries).

If so when I have the following code in my html file

topics.html:

<ul>
  {% for topic in topics %}
    <li>{{ topic }}</li>
  {% empty %}
    <li>No topics have been added yet.</li>
  {% endfor %}
</ul>

why do I need pass the data stored in topics into a context dictionary for topics.html to loop through and display the data? why not loop through the topics variable itself? I'm just confused on the use of "contexts"

Thanks for the help in advance.

You are returning a HttpResponse which doesn't know what to put in to the html for any given {{var}} so in the dictionary you are saying, if you see a any of the keys in my context, replace it for its value. Since you are returning a function, the only way to make the function know what to work with is putting it as an argument in it.

Also, Model.objects.all() does not return a list rather it returns a lazy queryset objects in which you can do stuff like

for x in Model.objects.all():
    x.one_of_the_fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM