0

I have a model that I would like to populate with csv data, I have followed a few tutorials on this and am now trying to do it on my own. This is the code that I have so far;

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings')

import django
django.setup()

#Import models
from app_name.models import Instance

# Third Party Imports
import pandas as pd

# Pull csv data into script
file  = 'path/to/file/filename.csv'
collected_data = pd.read_csv(file,index_col='Timestamp')
# this is a dataframe with three columns and a datetime index

for timestamp, row in collected_data.iterrows():
    info1 = row[0]
    info2 = row[1]
    info3 = row[2]

    inst = Instance.objects.get_or_create(timestamp = timestamp,
            info1 = info1,
            info2 = info2,
            info3 = info3)[0]

I am getting the following error, which I don't really understand, as I am quite new to Django.

SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

Let me know if there is any more information needed for a MCVE

Luka Vlaskalic
  • 445
  • 1
  • 3
  • 19

1 Answers1

1

Try to put your script into management command. Then you would have no problem with running only the ORM in standalone. The example you can find here: https://gist.github.com/kharandziuk/08de1d24845b05dfaa6acfbfda3cd28e

There is a long answer here: stackoverflow.com/questions/937742/use-django-orm-as-standalone

kharandziuk
  • 12,020
  • 17
  • 63
  • 121
  • Is it clear at all from my script why I am getting an error? I would quite like to understand what is wrong before trying something else. I will check out your example, thank you – Luka Vlaskalic Aug 27 '20 at 12:31
  • The script which I provide do much the same thing - uploading csv into memory. I believe the problem with your script: you trying to run Django Orm as standalone . There is a long answer here: https://stackoverflow.com/questions/937742/use-django-orm-as-standalone how to do it properly – kharandziuk Aug 27 '20 at 12:34
  • So it turns out that I was trying to run the script within Atom, using the Hydrogen package (which basically turns it into a Jupyter notebook) and that was not working, if I run the script from the terminal then it works fine. – Luka Vlaskalic Aug 27 '20 at 14:32