Importing via Pandas CSV into Django model manytomanyfield
Total newbie to Django. I decided to put my hand up at work to develop a small POC app but cannot seem to get past importing csv data via Pandas into my Django model manytomanyField. Everything else is working except for the m2m field.
Here is a portion of my model:
class Service_Interval(models.Model):
interval_name = models.CharField(null=True, max_length=200)
class Task(models.Model):
service_intervals = models.ManyToManyField(Service_Interval, related_name="intervals")
Here is my View:
def Import_Excel_pandas(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request. FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
#exceldata = pd.read_csv(filename, index_col ="Requirements")
df=pd.read_csv('sheets/import_csv/'+filename, sep=',', usecols=['ID','Requirements','Service Intervals','Task Created'])
#print(df)
row_iter = df.iterrows()
objs = [
Task(
id = row['ID'],
requirements = row['Requirements'],
task_created = row['Task Created'],
#service_intervals = row['Service Intervals'], << - dont work.
)
for index, row in row_iter
]
Task.objects.bulk_create(objs)
Here in some of the CSV:
I think I need to connect to connect/create in Service_Interval first then add to Tasks inside the loop somewhere, but I'm stuck on how/where to add the code within the object task and if the process is correct. Any help would be appreciated as I've been stuck on this for a while now.
intervals = row['Service Intervals']
service_intervals = ast.literal_eval(intervals)
service_intervals = map(str.lower, service_intervals)
service_intervals = list(set(service_intervals))
for interval_name in service_intervals:
service_intervals, _ = Service_Interval.objects.get_or_create(name=interval_name)
Task.service_intervals.add(service_intervals)