天天看点

django redirect传递参数_5个必读常用的Django小技巧

django redirect传递参数_5个必读常用的Django小技巧

如果你初学Django且英语不错,相信你大概率上过http://simpleisbetterthancomplex.com这个网站。作者生活在芬兰,写过很多关于Django技巧的原创英文文章。今天小编我就借花献佛,用中文辛苦搬运来5个我认为非常有用的Django小技巧,与大家分享。

Tip 5. 创建DateTimeField字段时使用auto_now_add和auto_now选项

当你在给一个模型创建一个DateTimeField类型的字段时,你可以设置auto_now_add=True和auto_now=True的选项。这样当你创建或更新一个时间字段时就不用手动指定或更新时间了。

class Article(models.Model):
    description = models.CharField(max_length=255)
    status = models.CharField(max_length=10)
    author = models.ForeignKey(User)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
           
  • auto_now_add

    在创建的时候自动设置字段为

    timezone.now()

  • auto_now

    在每次调用

    save

    方法都会更新为当前时间

创建模型各个字段时的注意事项见Django基础核心技术之Model模型的介绍与设计

Tip 4. 人性化显示(humanize)数字或时间

django.contrib.humanize

模块自带一组模板过滤器, 可将数字或者日期转化为人类友好可读的格式,更人性化。比如模板过滤器

naturaltime可以将2019-06-24 10:33:24

时间显示为

1 day ago。

使用该组模板过滤器时,你需要

在INSTALLED_APPS 加入django.contrib.humanize

模块,并在模板里载入,如下所示。

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
]
           

模板里先载入再使用。

{% load humanize %}

{{ notification.date|naturaltime }}
           

更多模板过滤器见Django基础(4): 模板(Template)的设计及常用过滤器与标签介绍

Tip 3. 使用redirect进行跳转

使用redirect比HttpResponseRedirect跳转更便捷,尤其在你需要跳转到某个视图,还需要给视图传递参数时。如下所示:

from django.shortcuts import redirect
from blog.models import Post

def post_view(request, post_id):
    return redirect('post_details', id=post_id)
    # equivalent to:
    return HttpResponseRedirect(reverse('post_details', args=(post_id, )))
           

redirect是django提供的便捷函数(shortcut function), 更多内容见Django基础(27): 快捷函数(shortcut function)模块详解.

Tip 2. 使用request在模板中获取当前url

在模板中你可以使用{{ request.path }}获取当前url,如果要获取带querystring的完整url你可以使用{{ request.get_full_path }}。如果你要获取完整绝对路径,你可以使用 {{ request.build_absolute_uri }}。具体使用方法如下所示:

https://jackeygao.io/search/?keyword=django

Method

Output

request.path

/search/

request.get_full_path

search/?keyword=django

request.build_absolute_uri

https://jackeygao.io/search/?keyword=django

Tip 1. 使用F方法更新一个对象或多个对象字段

通常情况下我们在更新数据时需要先从数据库里将原数据取出后放在内存里,然后编辑某些字段或属性,最后提交更新数据库。使用F方法则可以帮助我们避免将所有数据先载入内存,而是直接生成SQL语句更新数据库。

假如我们需要对所有产品的价格涨20%,我们通常做法如下。当产品很少的时候,对网站性能没影响。但如果产品数量非常多,把它们信息全部先载入内存会造成很大性能浪费。

products = Product.objects.all()
for product in products:
    product.price *= 1.2
    product.save()
           

使用F方法可以解决上述问题。我们直接可以更新数据库,而不必将所有产品载入内存。

from django.db.models import F

Product.objects.update(price=F('price') * 1.2)
           

我们也可以使用F方法更新单个对象的字段,如下所示:

product = Product.objects.get(pk=5009)
product.price = F('price') * 1.2
product.save()
           

但值得注意的是当你使用F方法对某个对象字段进行更新后,需要使用refresh_from_db()方法后才能获取最新的字段信息(非常重要!)。如下所示:

product.price = F('price') + 1
product.save()
print(product.price)            # <CombinedExpression: F(price) + Value(1)>
product.refresh_from_db()
print(product.price)            # Decimal('13.00')
           
小结

本文搬运来Django的5个常用小技巧,包括使用auto_now_add和auto_now选项设置时间字段,使用humanize人性化显示时间和数字,使用redirect进行跳转,使用request.get_full_path等方法在模板中获取当前链接及使用F方法更新对象字段,希望对大家有帮助哦。

大江狗

2019.08

django redirect传递参数_5个必读常用的Django小技巧