Django:从表中获取数据并使用ListView一起显示

Django: get data from tables and display together using ListView

我想显示 2 个表中的数据(将来会更多),但我的代码中有些东西不起作用。

我的views.py:

**imports**
def home(request):
    context = {'users': Person.object.all(),
               'emails': Email.object.all()
              }
    return render(request,'app/home.html',context)

class PersonListView(ListView):
    model = Person
    template_name = 'app/home.html'
    context_object_name = 'users'

在我的 home.html

{% extends "app/base.html" %}
{% block content %}
    {% for user in users %}
    Displaying user attributes works fine
    {% endfor %}

Here should be emails
{% for email in emails %}
    This displaying doesnt work
{% endfor %}
{% endbock content %}

因此,显示用户没有任何问题,但无法显示任何形式的电子邮件,但如果我在 shell 中这样做,一切正常

一个ListView [Django-doc] is designed to display only one queryset at a time. If you need to pass extra querysets, you can override the get_context_data(..) method [Django-doc]:

class PersonListView(ListView):
    model = Person
    template_name = 'app/home.html'
    context_object_name = 'users'

    def <b>get_context_data</b>(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update(<b>emails=Email.objects.all()</b>)
        return context

这里我们传递一个额外的变量emails给模板渲染引擎。但是请注意,此查询集不会 分页 (或者至少不会自己添加一些分页)。

my models.py:

注意那些是views,你需要把这些写在views.py.