【问题标题】:How to define get_queryset, get_context_data in a django view?如何在 django 视图中定义 get_queryset、get_context_data?
【发布时间】:2014-10-06 06:40:13
【问题描述】:

我想在子项目中显示为每个作者编写的 Authors 和 Books 的树, 比如show in the image 和...我有两个模型Author 和Book 处于OneToMany 关系中。

#models.py
from django.db import models

class Author(models.Model):
    Name = models.CharField(max_length = 250)

    def __unicode__(self):
        return self.Name

class Book(models.Model):
    Title = models.CharField(max_length = 250)

    def __unicode__(self):
        return self.Title


#views.py
from django.shortcuts import render, get_object_or_404
from django.views.generic import TemplateView, ListView

from .models import InstanciaJudicial, SedeJudicial

class Prueba(ListView):
    model = SedeJudicial
    template_name = 'instancias/pruebas.html'

我知道我定义了get_queryset 和get_context_data,但我不知道我是怎么做到的。

【问题讨论】:

  • 模型之间的关系在哪里?

标签: python django django-models django-templates django-views


【解决方案1】:

首先,您需要在模型之间建立ForeignKey 关系。

#models.py
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length = 250)
    author = models.ForeignKey(Author, related_name="books")

    def __unicode__(self):
        return self.Title

现在,在您看来,您应该能够通过重写 get_queryset 方法来检索您的作者列表,如下所示:

#views.py
from django.shortcuts import render, get_object_or_404
from django.views.generic import TemplateView, ListView

from .models import Author

class BooksByAuthorList(ListView):
    model = Book
    template_name = 'instancias/pruebas.html'

    def get_queryset(self):
        return Author.objects.prefetch_related("books").all()

仅使用上面的视图,您应该能够在模板中拥有:

<ul>
{% for author in object_list %}
  <li>{{author.name}}</li><ul>
  {% for book in author.books.all %}
    <li>book.title</li>
  {% endfor %}
  </ul>
{% endfor %}
</ul>

现在假设您要对其进行自定义,以便上下文变量代替通用的 object_list,而是在域中像 authors 这样的合理变量。

像这样增强你的视图:

class BooksByAuthorList(ListView):
    model = Author
    template_name = 'instancias/pruebas.html'
    context_object_name = 'authors'        

    def get_queryset(self):
        return Author.objects.prefetch_related("books").all()

请注意,您根本不需要get_context_data。

假设您想要包含一些额外的数据,您只想覆盖 get_context_data,在这种情况下,您需要通过首先调用超类 get_context_data 方法来保留已经在您的上下文中的对象列表.

只要做:

    def get_context_data(self, *args, **kwargs):
        # Call the base implementation first to get a context
        context = super(BooksByAuthorList, self).get_context_data(*args, **kwargs)
        # add whatever to your context:
        context['whatever'] = "MORE STUFF"
        return context

get_context_data 参数由您的路由决定。 *args 和 **kwargs 应该在实际代码中替换为特定于您的视图和路由的内容。

【讨论】:

  • @stderrt,感谢您的耐心和时间,我尝试使用此代码,但在模板中,我将 book.title 行修改为 {{ book.title }},然后,得到以下错误:“RelatedManager”对象不可迭代,
  • 我,解决了将 .all 添加到第二个问题:{% for book in author.books.all %}
  • book.title
  • {% endfor %}
猜你喜欢
相关资源
最近更新 更多
热门标签