当前位置: 代码迷 >> python >> 如何在基于类的视图(模板视图)中进行多个模型查询
  详细解决方案

如何在基于类的视图(模板视图)中进行多个模型查询

热度:116   发布时间:2023-06-13 14:15:26.0

我正在一个Django项目中,我有3个模型Books,Chapters,Topics。

我想显示用户界面中所有书籍的列表。 当用户单击任何一本书时,将显示所有章节,而当用户单击任意一章时,将显示所有主题。

我正在尝试使用基于类的视图。 要获取书籍列表,请查看.py

class read_books(TemplateView):
model = books
template_name='books_list.html'    
def get_context_data(self, *args, **kwargs):
    ctx = super(read_books, self).get_context_data(*args, **kwargs)
    ctx["books"]=books.objects.all()
    #here is the problem
    ctx["chapters"]=chapters.objects.filter(book_id=4)
    return ctx

和books_list.html作为

<script>
    $(document).ready(function(){
        $("#child").hide();
        $("#parent").click(function(){
        $("#child").show();
        });
    });
</script>
</head>

 <div id="parent" class="nav-width center-block">
    {% for wb in books %}
        <button>{{ wb.book_name }}</button>
        </br></br>
    {% endfor %}
</div>


<div id="child">
    {% for s in chapters %}
    <a href="">{{s.sheet_name}}</a>
    </br></br>
    {% endfor %}
</div>
{% endblock %}

现在我很麻烦,将有一个带有ID的书籍清单。 我现在要手动传递它的ID'ctx [“ chapters”] = chapters.objects.filter(book_id = 4)'。 任何人都可以提出建议并帮助如何从电子书模型中获取ID并将其传递给此查询。任何帮助都将得到高度重视。

如果您要坚持使用CBV,则应该具有以下内容

class BookList(ListView):
   model = Book

# the below would show the details of particular chapters for a specific book

class BookDetail(DetailView):
   model = Book

#and so on
class chapterList(ListView):
   model = Chapter

on your html - link the urls to each book/chapter by using their respective pks

<a href = '{% url "book" pk = obj.pk %}'></a>

好的,假设您想将您的视图实现为TemplateView (但是在不同模型上返回相同的结果和一些附加查询。您可以执行以下操作:

# models.py
class Book(models.Model):
    ...

class Model1(models.Model): 
    ...

class ModelN(models.Model):
    ...

# views.py
class BookTemplateView(TemplateView):

    def get_context_data(self, *args, **kwargs):
        ctx = super(BookTemplateView, self).get_context_data(*args, **kwargs)
        ctx["books"] = Book.objects.all()
        ctx["data_1"] = Model1.objects.all() # you can refine this, of course
        ...
        ctx["data_n"] = ModelN.objects.all() # you can refine this, of course

        return ctx

Book_list.html您可以编写以下内容(摘自您的问题):

{% for wb in books %}
  <button>{{ wb.book_name }}</button>
  </br></br>
{% endfor %}

...
{% for object in data_1 %}
    ... do something meaningful ...
{% endfor %}
...
{% for object in data_n %}
    ... do something meaningful ...
{% endfor %}

请注意,如果BookTemplateView是从ListView继承的,则这将完全相同,然后您无需分配ctx["books"] = Book.objects.all() (这就是为什么在我看来DRY更少的原因方法)

这接近您喜欢做的事吗?

  相关解决方案