Django导出主要使用render_to_string方法来进行;
可以参考的源码如下:
from article.models import Article from django.template.loader import render_to_string posts = Article.objects.all() for post in posts: title = post.title title = title.replace('[', '') title = title.replace(']', '') context = { 'title': title, 'cre_date': post.cre_date, 'updated': post.up_date, 'content': post.content, 'category': post.category.name, 'tag': post.tag } content = render_to_string('article.html', context) filename = 'export/' + post.title + '.md' with open(filename, 'w') as f: f.write(content)
对应的渲染article.html
title: {{ title }}
date: 2018-01-05T01:00:00+08:00
updated: {{ updated | date:"Y/m/d H:i:s" }}
tags: [
{% for tag in tags %}
'{{ tag.name }}',
{% endfor %}
]
categories: [
'{{ category }}',
]
---
{{ content | safe }}
运行的时候,python manage.py shell,然后导入export 包即可。