Django 进阶杂记

数据导入

  • 将文件内容导入,下面是3种方式。
# blogs.txt文件
title 1****content 1
title 2****content 2
title 3****content 3
title 4****content 4
title 5****content 5
title 6****content 6
title 7****content 7
title 8****content 8
title 9****content 9
def main ():
    file = open('blogs')
    for line in file:
        title ,content = line.split('****')
        Blogs.objects.get_or_create(title=title,content=content)#这样写会避免重复,但效率会慢些
    file.close()
def main():
    file = open('blogs')
    blogList=[]
    for line in file:
        title ,content = line.split('****')
        blog = Blogs(title=title,content=content)#创建Blogs对象
        blogList.append(blog)
    file.close()
    Blogs.objects.bulk_create(blogList)
def main():
    os.system('python3 manage.py loaddata blog_dump.json')
  • 清除数据库内容python3 manage.py flush

数据迁移

  • 简单的数据库导出迁移,对于结构复杂的会出现导出错误
#将app中的数据导出成json文件,不写app名默认为所有应用
python3 manage.py dumpdata appName > appName.json
#导出用户数据
python3 manage.py dumpdata auth > auth.json

Django 缓存

@cache_page(60 * 15) # 秒数,这里指缓存 15 分钟,不直接写900是为了提高可读性
def index(request):
    # 读取数据库等 并渲染到网页
    return render(request, 'index.html', {'queryset':queryset})
访问一个网址时, 尝试从 cache 中找有没有缓存内容
如果网页在缓存中显示缓存内容,否则生成访问的页面,保存在缓存中以便下次使用,显示缓存的页面。
given a URL, try finding that page in the cache
if the page is in the cache:
    return the cached page
else:
    generate the page
    save the generated page in the cache (for next time)
    return the generated page
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值