[英]How to define get_queryset, get_context_data in a django view?
我希望在子项目中为每个作者显示一个带有Authors
和Books
的树,如图像中的显示和......我在OneToMany关系中有两个模型Author
和Book
。
#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
,但我不知道我是怎么做到的。
首先,您需要在模型之间建立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
可能应该替换为您的视图中特定的内容并在实际代码中路由。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.