Loading csv data in database

40 views
Skip to first unread message

Muhammad Asim Khaskheli

unread,
Apr 29, 2021, 12:13:28 PM4/29/21
to Django users

Hi,

I wanted to ask how to load CSV data into the model. What steps do we have to follow?

I have made this function but how exactly to run this code because, python manage.py load data won't work.

def import_data():
with open('sample-dataset.csv') as f:
reader = csv.reader(f)
for row in reader:
if row[0] != 'user_id':
_, created = Funnel.objects.get_or_create(
user_id=row[0],
event=row[1],
timestamp=row[2],
session_id=row[3]
)

Now, how to run this script?


Ryan Nowakowski

unread,
Apr 29, 2021, 1:39:36 PM4/29/21
to django...@googlegroups.com
Typically you would write a custom management command for this kind of thing:

https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/

Nauman Khan gori

unread,
Apr 29, 2021, 4:18:21 PM4/29/21
to Django users
you may use pandas for this 
you can use it as follows:-
first install it
if not using python from anaconda environment!

pip install pandas
import pandas as pd
reader=pd.read_csv("sample-dataset.csv")
reader.head(3) # for viewing top 3 rows.

hope this may help you
 -)-)

Derek

unread,
Apr 30, 2021, 10:49:40 AM4/30/21
to Django users
Someone has an example of doing just this:

Amitesh Sahay

unread,
Apr 30, 2021, 11:04:14 AM4/30/21
to Django users

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/137aee79-07e6-40e1-badd-671ae3b0c87cn%40googlegroups.com
.
Reply all
Reply to author
Forward
0 new messages