gpt4 book ai didi

Django DetailView 按外键过滤

转载 作者:行者123 更新时间:2023-12-04 05:17:22 30 4
gpt4 key购买 nike

我有点困惑,并希望利用 DetailView 功能使用外键作为我的过滤器来显示数据。基本上我的模型是这样的:

class Category(models.Model):
name = models.CharField(max_length=30)
slug = models.SlugField(help_text="A short name for Category")

def __unicode__(self):
return self.name

class Meta:
ordering = ["-name"]
verbose_name_plural = "categories"


class Publisher(models.Model):
name = models.CharField(max_length=30)
slug = models.SlugField(help_text="A short name for Publisher")

class Meta:
ordering = ["-name"]

def __unicode__(self):
return self.name


class Book(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(help_text="A short name for book")
pub_date = models.DateField()
publisher = models.ForeignKey(Publisher)
category = models.ForeignKey(Category)

class Meta:
ordering = ["-title"]

def __unicode__(self):
return self.title

我的网址:
url(r'^categories/(?P<slug>[\w-]+)/$', DetailView.as_view(model=Category,template_name="books/category_detail" )),

我的 Category_detail.html
{% block content %}
<h2>{{ category.name}} </h2>
<ul>
<li>Book Title: {{ book.title }}</li>
<li>Book publisher: {{ book.publisher }}</li>
<li>Book Published Date: {{ book.pub_date }}</li>
</ul>
{% endblock %}

基本上我想在我的 category_detail.html 中显示以下信息:
  • 分类名称
  • 书名
  • 出版商名称
  • 发布日期

  • 任何帮助将不胜感激。

    谢谢 - Keoko

    最佳答案

    感谢您的友好回应。我创建了一个包含以下信息的 views.py 文件:

    from django.shortcuts import get_object_or_404
    from django.views.generic import ListView
    from mysite.books.models import *

    class BooksCategoryListView(ListView):

    context_object_name = "book_list"

    "get_queryset = query all the objects in the database"
    def get_queryset(self):
    category_slug = get_object_or_404(Category, slug=self.kwargs['slug'])
    return Book.objects.filter(category=category_slug)

    并更新了我的应用程序 urls.py:
    from django.conf.urls import patterns, url, include
    from django.views.generic import ListView, DetailView
    from mysite.books.views import BooksCategoryListView
    from mysite.books.models import *

    urlpatterns = patterns('',
    ...snip....
    url(r'^categories/(?P<slug>[\w-]+)/$', BooksCategoryListView.as_view()),
    )

    最后修改 category_detail.html 如下:
    {% block content %}
    <h2>Book Details</h2>
    <ul>
    <li>Category: {{ book.category}}</li>
    <li>Title: {{ book.title }}</li>
    <li>Author: {{ book.authors }}</li>
    <li>Publisher: {{ book.publisher }}</li>
    <li>Published Date: {{ book.pub_date }}</li>
    </ul>
    {% endblock %}

    关于Django DetailView 按外键过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14092482/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com