models.py
from django.db import models
class Human(models.Model):
name = models.CharField('name', max_length=200)
age = models.IntegerField('age', null=True, blank=True)
def __str__(self):
return self.name
Normally, when you create an object in Django, you write it like this:
taro = Human.objects.create(name='Taro', age=30)
taro.save()
hanako = Human(name='Hanako', age=2)
hanako.save()
There should be no problem.
models.py
class TestModel(models.Model):
field_1 = models.CharField('Field 1', max_length=255)
field_2 = models.CharField('Field 2', max_length=255)
...
field_50 = models.IntegerField('Field 50', null=True)
def __str__(self):
return self.field_23
A case where you want to input a DB from a CSV file with 50 items through Django's ORM. If you try to do it like a Ueno Human model
df = pd.read_csv('test_data.csv')
for _, row in df.iterrows():
t = TestModel.objects.create(field_1=row[0], field_2=row[1], field_3=row[2]....)
It's not crazy to write 50 pieces.
df = pd.read_csv('test_data.csv')
for _, row in df.iterrows():
dict_data = row.to_dict()
t = TestModel.object.create(**dict_data)
smart!
In Python, you can pass a list, tuple, or dictionary as a function argument while expanding it.
https://note.nkmk.me/python-argument-expand/
Recommended Posts