Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使django的所有URL都达到slug级别?_Python_Django - Fatal编程技术网

Python 如何使django的所有URL都达到slug级别?

Python 如何使django的所有URL都达到slug级别?,python,django,Python,Django,如何使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 exampl

如何使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()
然后我将在我的文章模型中使用它,如下所示:

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()

然后,我的mane url.py文件中只有一个url字段:

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

我需要这一点,因为如果有一天我决定将/articles改为/blog,那么我将在谷歌搜索中破坏数百个URL。

你的想法几乎完美无瑕。我只建议进行以下更改:

1) 似乎不需要
链接
模型。您
slug
可以是
文章
模型本身内部的
CharField

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

2) 评论属于文章。因此,与其让
Review
拥有指向此
链接的
ForeignKey
对象(该链接不应再存在),不如让
ForeignKey
指向
文章

,但我如何检查slug是否唯一?例如,如果我创建blog post example.com/google-review,然后我使用slug-google-review创建评论,那么哪个链接应该是example.com/google-review-Reviews是具有不同模型的不同应用程序。您可以在模型本身中约束这一点。请参阅更新的answerclass BaseContent(models.Model):slug=models.SlugField()class Meta:abstract=True我决定创建由所有模型继承的基类。但现在我不知道如何为每个应用程序创建视图。因为之前每个应用程序都有一个带有视图的url。例如,我需要两个不同应用程序的两个视图。每个应用程序存储不同的信息并具有不同的模板。我应该如何使输入的url触发器正确查看?