如何使脚本在我的默认sqlite3数据库django中插入数据 [英] How to make a script to insert data in my default sqlite3 database django

查看:201
本文介绍了如何使脚本在我的默认sqlite3数据库django中插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Django中定义了我的模型以及所有模型,如果用户通过我的应用程序进行注册,则该用户可以很好地在数据库中注册。问题是我有一个包含有大量用户的JSON的文件。
我想做一个允许我读取此文件并将所有用户插入数据库的工作。

I have defined my model and all in Django and if a user is registering via my application the user is well register in the database. The problem is I have a file containing a JSON with plenty of users. I want to do a job that allow me to read this file and insert all the user in my database.

做这件事的最佳方法是什么?如何在不使用Django的情况下连接到数据库?

What is the best way to do it? How to connect to the Database without using Django?

推荐答案

为什么要在没有Django的情况下连接到数据库?我会使用Django来执行此操作,但是您需要初始化Django,以便能够针对它运行脚本。

Why do you want to connect to the database without Django? I would do it using Django, but you need to initialize Django, to be able to run scripts against it. Something like this should do it:

import os, sys
sys.path.append('/path/to/django/project')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project_name.settings'
import django
django.setup()
from django.contrib.auth.models import User

for row in data:
    user = User.objects.create_user(username=row['username'])

/ path / to / django / project 是包含设置的目录所在的文件夹的路径。例如,层次结构为:

/path/to/django/project is the path to the folder where the directory containing your settings is. For example with hierarchy of:

/projects/my_project
/projects/my_project/my_app
/projects/my_project/my_project/setting.py

您需要附加 / projects / my_project

如果您需要使用Django User 模型代替自定义模型,而不是

If instead of the Django User model you need to work with a custom model, instead of

from django.contrib.auth.models import User

do

from app_name.models import ModelName

这篇关于如何使脚本在我的默认sqlite3数据库django中插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆