【问题标题】:How to make django all urls be to level slug?如何使 django 的所有 url 成为水平 slug?
【发布时间】:2016-12-09 18:52:29
【问题描述】:

如何使 django 的所有 url 成为顶级 slug? 顶级 slug 我的意思是所有 url 都有独特的 slug 示例:

example.com/articles
example.com/article-1
example.com/article-2
example.com/article-3
example.com/reviews
example.com/reviews-1
example.com/reviews-2
but not:
example.com/articles/article-1
example.com/articles/article-2
example.com/articles/article-3
example.com/reviews/reviews-1
example.com/reviews/reviews-2

我有很多应用,例如文章、评论和其他自定义页面。

那么,您对我使用这样的模型创建应用程序的这种方法有何看法:

class Link(models.Model):
    slug = models.SlugField(unique=True)

然后我将在我的文章模型中使用它,如下所示:

from links.models import Link

class Article(models.Model):
    title = models.CharField()
    slug = models.OneToOneField(
        Link,
        on_delete=models.CASCADE,
        primary_key=True,
    )
    body = models.TextField()

.

from links.models import Link

class Review(models.Model):
    title = models.CharField()
    slug = models.OneToOneField(
        Link,
        on_delete=models.CASCADE,
        primary_key=True,
    )
    review = models.TextField()

然后我的鬃毛 urls.py 文件中将只有一个 url 字段:

url(r'^(?P<slug>[-_\w]+)', views.link, name='link'),

现在我应该如何过滤我想要返回文章或评论的数据?

这样还是有更好的解决方案?

from django.http import HttpResponseRedirect

from .models import Link
from articles.models import Article
from review.models import Review

def link(request, link):
    link = Link.objects.get(link=link)
    if Article.objects.filter(slug=Link).exists():
        link = link.slug
        return HttpResponseRedirect(link)

    if Review.objects.filter(slug=Link).exists():
        link = link.slug
        return HttpResponseRedirect(link)

    return HttpResponseRedirect('/')

Google 需要它,因为如果我决定有一天将 /articles 更改为 /blog,那么我将在 google 搜索中破坏数百个 url。

【问题讨论】:

    标签: python django


    【解决方案1】:

    你的想法几乎是完美的。我只推荐更改:

    1) 似乎不需要Link 模型。你 slug 可以是 CharField 内部的 Article 模型本身

    class Article(models.Model):
        title = models.CharField()
        slug = models.CharField(max_length=255, unique=True)
        body = models.TextField()
    

    2) 评论属于文章。因此,与其将 Review 与不应再存在的 Link 对象的 ForeignKey 不同,不如将 ForeignKey 与 Article 相匹配

    【讨论】:

    • 但是我如何检查 slug 是否是唯一的?例如,如果我创建博客文章 example.com/google-review,然后我使用 slug google-review 创建评论,哪个链接应该是 example.com/google-review 评论是具有不同模型的不同应用程序。
    • 您可以在模型本身中对此进行约束。查看更新的答案
    • class BaseContent(models.Model): slug = models.SlugField() class Meta: abstract = True 我决定创建所有模型都继承的基类。但现在我不知道如何为每个应用程序创建视图。因为在每个应用程序都有带有视图的 url 之前。例如,我需要两个不同应用程序的两个视图。每个应用程序存储不同的信息并具有不同的模板。我应该如何让输入的 url 触发正确的视图?
    猜你喜欢
    • 2018-02-12
    • 2014-10-02
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 2022-01-15
    • 2020-04-19
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多