Class based views query: get objects referenced by another model

我只是一个虾纸丫 提交于 2019-12-13 04:03:33

问题


this question extends Django Pass Multiple Models to one Template

In that I want to produce 1 template, that is my profile index page, so it will list all the objects created by the user specified in the url

I want to query multiple models for one template, get the Profile in question and show all the oferto objects that was created by the attached profile

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 I am thinking I need to get the profile slug from the url in order to search for all oferto by that user in the url

url(
regex=r"^index/(?P<slug>[-_\w]+)",
view=ProfileIndex.as_view(),
name="profile_index",
),

And this has been the hardest to figure out, how to make my template work correctly from the context in question

{% 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 %}

回答1:


frontend/models.py

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

Class Oferto(models.Model): 
   profile = model.ForeignKey(Profile):
   ...

frontend/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 %} 



回答2:


You don't state what your problem is exactly. But there are two issues with the syntax you're using in the query of Oferto: first, kwargs is a dictionary which has a "slug" key (no idea why you've put profile in there), and secondly you need to provide a field name to query against.

It should be:

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


来源:https://stackoverflow.com/questions/20863495/class-based-views-query-get-objects-referenced-by-another-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!