如题所述
django1.9.5&python3.4.4
文件结构
在一个爬虫脚本中将爬取的数据通过django自带的model保存到数据库
修改的文件(其余pycharm新建Django项目生成,未修改):
# testapp/models.pyfrom django.db import models class Problem(models.Model): title = models.CharField(max_length=100, default="") author = models.CharField(max_length=100, default="") def __str__(self): return self.title pass
# testapp/spider.pyimport osimport sysimport django pathname = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, pathname)sys.path.insert(0, os.path.abspath(os.path.join(pathname, '..')))os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings") django.setup() from testapp.models import Problem if __name__ == "__main__": p = Problem(title="hi", author="hi") p.save() pass
# testproject/setting.py......INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 添加应用 'testapp',]......
# testapp/admin.py 在后台管理界面注册 Problemfrom django.contrib import admin # Register your models here. from testapp.models import Problemadmin.site.register(Problem)
运行spider.py,添加一条实例记录
运行Django项目, 创建管理员账号, 后台管理界面查看结果