【问题标题】:Class based views query: get objects referenced by another model基于类的视图查询:获取另一个模型引用的对象
【发布时间】:2014-01-18 18:03:52
【问题描述】:

这个问题延伸 Django Pass Multiple Models to one Template

我想制作1个模板,即我的个人资料索引页面,所以它会列出url中指定的用户创建的所有对象

我想为一个模板查询多个模型,获取相关配置文件并显示由附加配置文件创建的所有 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

urls.py 我想我需要从 url 获取配置文件 slug 以便在 url 中搜索该用户的所有 oferto

url(
regex=r"^index/(?P<slug>[-_\w]+)",
view=ProfileIndex.as_view(),
name="profile_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 %}

【问题讨论】:

    标签: python django django-class-based-views


    【解决方案1】:

    你没有说明你的问题到底是什么。但是你在 Oferto 的查询中使用的语法有两个问题:首先,kwargs 是一个字典,它有一个“slug”键(不知道你为什么把 profile 放在那里),其次你需要提供要查询的字段名称。

    应该是:

    context['oferto'] = Oferto.objects.get(slug=kwargs['slug'])
    

    【讨论】:

      【解决方案2】:

      前端/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'
      

      前端/模板/前端/view_profile_list.html

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

      【讨论】:

        猜你喜欢
        • 2012-10-09
        • 2017-08-13
        • 2013-02-04
        • 2021-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-01
        • 2017-10-18
        相关资源
        最近更新 更多