首页 > 解决方案 > 蛞蝓唯一性问题的解决方案或如何找到我需要的蛞蝓

问题描述

同事们,下午好!有样板书和样板章。每本书都有很多章节。每章都绑定到特定的书,如果章的 slug 是唯一的,那么当 book1 - chapter1,我无法创建 book2 - Chapter 2 时,会产生错误。如果您使 slug 不唯一,则会发出一个错误,即需要一个参数,但传递了 2 个参数。

我怎么解决这个问题?我希望 slug 是一个数字,django 明白,沿着路径 / book1 / 1 / 你需要拿一个编号为 1 的 slug,它专门与 book1 相关联,而不是注意编号为 1 的 slug,但是绑定到 book2。

如果蛞蝓是独一无二的,那么我会平静地找到正确的书和正确的章节,但是当我需要按预期到达那里时,一切都会崩溃。

路径是这样构建的:/book1/1(章节)/etc.book2/1/etc

class Book(models.Model):
    some code

class Chapter(models.Model):
   book= models.ForeignKey(Book, verbose_name="title", on_delete=models.CASCADE)
   number = models.PositiveIntegerField(verbose_name="num chapter")
   slug = models.SlugField(unique=True, verbose_name="slug_to", null=True, blank=True)

   def save(self, *args, **kwargs):
        self.slug = self.number
        super().save(*args, **kwargs)

Views.py

class Base(View):
    def get(self, request, *args, **kwargs):
        book = Book.objects.all()
        return render(request, "base.html", context={"book": book})


class BookDetail(DetailView):
    model = Book
    context_object_name = "book"
    template_name = "book_detail.html"
    slug_url_kwarg = "slug"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["chapter"] = Chapter.objects.filter(title=self.object)
        return context


class ChapterRead(DetailView):
    model = Chapter
    context_object_name = "chapter"
    template_name = "chapter_read.html"
    slug_url_kwarg = "int"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["imgs"] = ImgChapter.objects.filter(chapter=self.object)
        return context


urls.py 

from django.contrib import admin
from django.urls import path
from .views import *


urlpatterns = [
    path("", Base.as_view(),name="book_list"),
    path("<str:slug>/", BookDetail.as_view(), name="book_detail"),
    path("<str:slug>/<str:int>/", ChapterRead.as_view(), name="chapter_detail")
]


html

base.html 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tf</title>
</head>
<body>

{% for i in book%}
    <a href="{{ i.slug }}"> {{i.name}}</a>
{% endfor %}


</body>
</html>

book_detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ book.name }}
{% for i in chapter %}
<a href="{{ i.slug }}">{{ i.number }}</a>
{% endfor %}
</body>
</html>

chapter_read.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

{{ chapter.number }}

{% for i in imgs %}

    <img src="{{ i.img.url }}">

{% endfor %}

</body>
</html>

标签: djangodjango-viewsrequestslug

解决方案


推荐阅读