将 slug 保存到数据库或动态生成更好?
我正在开发一个 django 项目,希望在 url 末尾包含一个 slug,就像 stackoverflow.com 上所做的那样: http://example.com/object/1/my-slug- generated-from-my-title
对象 ID 将用于查找向上的是项目,而不是 slug——并且,像 stackoverflow.com 一样,在获取链接时(仅在显示链接时),slug 根本不重要。
问题:动态生成 slug 而不是将其保存为实际的数据库字段是否有缺点(或优点)?
例如(不是真实代码):
class Widget(models.Model):
title = models.CharField()
def _slug(self):
return slugify(self.title)
slug = property(_slug)
而不是使用类似 AutoSlugField 的东西(例如)?
由于我的计划是使其与标题相匹配,因此我不知道数据库中存在重复字段是否有意义。
谢谢!
I am working on a django project and would like to include a slug at the end of the url, as is done here on stackoverflow.com: http://example.com/object/1/my-slug-generated-from-my-title
The object ID will be used to look up the item, not the slug -- and, like stackoverflow.com, the slug won't matter at all when getting the link (just in displaying it).
Qestion: is there a downside (or upside) to generating the slug dynamically, rather than saving it as an actual database field ?
For example (not real code):
class Widget(models.Model):
title = models.CharField()
def _slug(self):
return slugify(self.title)
slug = property(_slug)
Rather than using an something like an AutoSlugField (for example) ?
Since my plan is to have it match the title, I didn't know if it made sense to have a duplicate field in the database.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您将 slug 用于装饰(而不是查找)目的,那么动态生成它是最好的主意。
此外,您发布的代码示例可以这样写:
If you're using the slug for decorative (rather than lookup) purposes, generating it dynamically is the best idea.
Additionally, the code sample you posted can be written like this:
尝试用“咖啡馆”或“浦安鉄筋家族”这个词制作一条鼻涕虫。
除非你真的做好了充分的准备,否则它很可能看起来像便便。
有时您需要能够自定义 slugs。
Try making a slug out of the word "café" or "浦安鉄筋家族".
Chances are that it'll look like poo, unless you're really well-prepared.
Sometimes you need the ability to customize slugs.
缺点是每次渲染页面时都会自动生成 slug。这样做的好处是,永远不会直接查询的字段不会占用数据库中的空间。
无论哪种方式都可以,这仅取决于您的性能与空间要求。
The downside would be that you're automatically generating the slug every time you render the page. The upside is that you're not taking up space in the database with a field that will never be directly queried against.
Either way is fine, it just depends on your performance vs. space requirements.
动态生成 slugs 的主要缺点是您无法为每个对象自定义 slugs,例如。让它们更短更漂亮。对于英文标题,这可能没问题,但对于非英文内容,生成的 slugs 可能会很难看。
The main downside of generating slugs dynamically is that you miss the ability to customize slugs per-object, eg. make them shorter and prettier. For English titles this can be OK, but for non-English content generated slugs can be ugly.