Django中的@permalink和get_absolute_url是什么? [英] What is @permalink and get_absolute_url in Django?

查看:99
本文介绍了Django中的@permalink和get_absolute_url是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django中的 @permalink get_absolute_url 是什么?何时和为什么使用它?



请一个非常简单的例子(一个真正的实际例子)。谢谢

解决方案

@permalink 是一个python 装饰器,而 get_absolute_url 是django模型上的一种方法。 >

两者都涉及允许您反转特定对象的URL,并且应该一起使用。只要您需要提供特定对象的链接,或者想要将该对象的特定URL(如果有的话)显示给用户,就可以使用它们。



您可以简单地写您的 get_absolute_url 方法返回一个硬编码的字符串,但这不会坚持Django的DRY理念(不要重复你自己)。相反,有 @permalink 使事情更加灵活。



如果您阅读该主题的文档,您将看到它们如何相互关联。 @permalink 装饰器挂接到django的URLconf后端,允许您使用命名的url模式。这比使用它自己的 get_absolute_url 更为可取,因为您不需要指定路径,因此您的代码变得更加DRYer。

  class BlogPost(models.Model):
name = modelsCharField()
slug = models.SlugField (...)

@permalink
def get_absolute_url(self):
return(blog-detail,[self.slug,])

和urls.py

  ... 
url(r'/ blog /(?P< slug> [ - w] +)/ $',blog.views.blog_detail,name =blog-detail)


What is @permalink and get_absolute_url in Django? When and why to use it?

Please a very simple example (a real practical example). Thanks

解决方案

@permalink is a python decorator, while get_absolute_url is a method on a django model.

Both are concerned with allowing you to reverse the URL for a particular object and should be used together. They are used anytime you need to provide a link to a particular object or want to display that object's specific URL (if it has one) to the user

You could simply write your get_absolute_url method to return a hard coded string, but this wouldn't adhere to Django's philosophy of DRY (don't repeat yourself). Instead, there is the @permalink to make things more flexible.

If you read the docs on the subject you will see how they relate to each other. the @permalink decorator hooks into django's URLconf's backend, allowing you to write much more portable code by using named url patterns. This is preferable to just using get_absolute_url on it's own: your code becomes much DRYer as you don't have to specify paths.

class BlogPost(models.Model):
    name = modelsCharField()
    slug = models.SlugField(...)

    @permalink
    def get_absolute_url(self):
        return ("blog-detail", [self.slug,])

and in urls.py

    ...
    url(r'/blog/(?P<slug>[-w]+)/$', blog.views.blog_detail, name="blog-detail")

这篇关于Django中的@permalink和get_absolute_url是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆