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.
What is the best way to do it? How to connect to the Database without using 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
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
you you need to append /projects/my_project
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With