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
posted @ 2017-10-15 23:42  icanactnow  阅读(93)  评论(0编辑  收藏  举报