如何将两个模型对象传递给get_queryset视图?

时间:2016-11-12 03:46:12

标签: python django django-models django-views

所以我想要做的就是将另一个模型对象(问题)传递给我的视图。该视图当前返回另一个模型的get_queryset(Post)。所以这是我想要传递的上下文,所以我可以在polls.html

中呈现它
question = get_object_or_404(Question, id=1)
context = {'question': question})

urls.py

BV = BoxesView.as_view()

urlpatterns = [
    url(r'^$', BV, name='news')
]

view.py

class BoxesView(ListView):
    template_name = 'polls.html'

    def get_queryset(self):
        queryset_list = Post.objects.all().filter(category=1).order_by('-date')
        return queryset_list

polls.html

{% extends 'parent.html' %}

{% block polls %}

<p>question goes here</p> #this shows up
{{ question.question_text }} #this doesn't show up


{% endblock %}

parent.html

{% extends 'base.html' %}

{% block content %}

        {% for post in post_list %}

            {% block polls %}

            {% endblock %}

        {% endfor %}

{% endblock %}

models.py

class Post(models.Model):
    title = models.TextField(max_length=70)

class Question(models.Model):
    question_text = models.CharField(max_length=70)

2 个答案:

答案 0 :(得分:0)

您必须将其导入视图中。 from myapp.models import Questions。然后你可以使用它,例如:

question = Questions.objects.get(pk=1)

如果您拥有相同的模型名称,可以像这样导入: from myapp.models import Questions as Question1

答案 1 :(得分:0)

您需要覆盖get_context_data()方法:

class BoxesView(ListView):
    ...

    def get_context_data(self, **kwargs):
        context = super(BoxesView, self).get_context_data(**kwargs)
        question = get_object_or_404(Question, id=1)
        context['question'] = question
        return context

Here你可以找到类似的例子和其他有用的东西。