如何使django所有网址都达到水平slu ??

时间:2016-12-09 18:52:29

标签: python django

如何让django所有网址成为顶级slu g? 顶级slug我的意思是所有网址都有独特的slug示例:

print(self, "Doing something else...")
// Prints like: <MyModule.MyClass: 0x7fd190d0f270> Doing something else...
// Sometimes like: <_TtCC14__lldb_expr_668MyModule7MyClass: 0x7fd190d0f270> Doing something else...

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

那么,你如何看待我用这样的模型创建应用程序的方法:

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

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

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

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

像这样或者可能存在更好的解决方案?

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

我需要谷歌,因为如果我决定有一天更改/文章/博客,那么我将在谷歌搜索中打破数百个网址。

1 个答案:

答案 0 :(得分: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)评论属于文章。因此,ReviewForeignKey这个Link对象应该不再存在,而不是ForeignKey,而应该Articlestring search; // not initialized, You define it's type and it's name. string search = "something"; //initialized

相关问题