Django 进阶杂记

来源:互联网 发布:cms监控软件远程设置 编辑:程序博客网 时间:2024/06/11 00:33

数据导入

  • 将文件内容导入,下面是3种方式。
# blogs.txt文件title 1****content 1title 2****content 2title 3****content 3title 4****content 4title 5****content 5title 6****content 6title 7****content 7title 8****content 8title 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 cacheif the page is in the cache:    return the cached pageelse:    generate the page    save the generated page in the cache (for next time)    return the generated page
原创粉丝点击