簡體   English   中英

如何在django視圖中定義get_queryset,get_context_data?

[英]How to define get_queryset, get_context_data in a django view?

我希望在子項目中為每個作者顯示一個帶有AuthorsBooks的樹,如圖像中的顯示和......我在OneToMany關系中有兩個模型AuthorBook

#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_querysetget_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM