Python 基于类的视图查询:获取其他模型引用的对象

Python 基于类的视图查询:获取其他模型引用的对象,python,django,django-class-based-views,Python,Django,Django Class Based Views,这个问题延伸到 因为我想生成一个模板,即我的配置文件索引页,所以它将列出url中指定的用户创建的所有对象 url( regex=r"^index/(?P<slug>[-_\w]+)", view=ProfileIndex.as_view(), name="profile_index", ), 我想为一个模板查询多个模型,获取有问题的概要文件,并显示由附加概要文件创建的所有oferto对象 views.py class ProfileIndex(ListView): context

这个问题延伸到

因为我想生成一个模板,即我的配置文件索引页,所以它将列出url中指定的用户创建的所有对象

url(
regex=r"^index/(?P<slug>[-_\w]+)",
view=ProfileIndex.as_view(),
name="profile_index",
),
我想为一个模板查询多个模型,获取有问题的概要文件,并显示由附加概要文件创建的所有oferto对象

views.py

class ProfileIndex(ListView):
context_object_name = 'account_list'    
template_name = 'profiles/account_index.html'
queryset = Profile.objects.all()

def get_context_data(self, **kwargs):
    context = super(ProfileIndex, self).get_context_data(**kwargs)
    context['profile'] = Profile.objects.all()
    context['oferto'] = Oferto.objects.get(kwargs.profile.slug)

    return context
py我想我需要从url中获取概要文件slug,以便在url中搜索该用户的所有错误

url(
regex=r"^index/(?P<slug>[-_\w]+)",
view=ProfileIndex.as_view(),
name="profile_index",
),
url(
regex=r“^index/(?P[-\uw]+)”,
视图=ProfileIndex.as\u view(),
name=“profile\u index”,
),
这是最难弄清楚的,如何使我的模板在相关上下文中正确工作

{% block content %}

<h1>{{ profile }}<h1>
    <h2> Ofertoj or/aŭ Offers</h2>
    {% for oferto in profile  %}
        <a href="{% url "oferto_detail" oferto.slug %}">{{ oferto.name }}</a><br/>


    {% endfor %}




{% endblock %}
{%block content%}
{{profile}}
Ofertoj或/aŭ报价
{配置文件%中oferto的百分比}

{%endfor%} {%endblock%}
您没有确切说明问题所在。但是在Oferto查询中使用的语法有两个问题:第一,kwargs是一个有“slug”键的字典(不知道为什么要在其中放入profile),第二,需要提供一个字段名进行查询

应该是:

context['oferto'] = Oferto.objects.get(slug=kwargs['slug'])
前端/models.py

Class Profile(models.Model):
   ....

Class Oferto(models.Model): 
   profile = model.ForeignKey(Profile):
   ...
前端/views.py

Class ViewProfileList(ListView):
    model = Profile
    template_name = 'frontend/view_profile_list.html'
frontend/templates/frontend/view_profile_list.html

  {% for profile in object_list.all %}
      {% for ofer in profile.oferto_set.all %}
         {{ ofer.you_field }}
      {% endfor %}
  {% endfor %}