[PYTHON] [Django] What to do if the model you want to create has a large number of fields

I want to create an object

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.

What would you do in such a case?

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.

Pass it as an argument while expanding it into a dictionary!

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.

reference

https://note.nkmk.me/python-argument-expand/

Recommended Posts

[Django] What to do if the model you want to create has a large number of fields
Make a note of what you want to do in the future with Raspberry Pi
What to do if you can't create a virtual environment using venv even though you're following the Django official website
If you want to create a Word Cloud.
If you want to display values using choices in a template in a Django model
What to do if you get a UnicodeDecodeError with pip install
What to do if you can't use the trash in Lubuntu 18.04.
What to do if you cat or tail a binary file and the terminal is garbled
[Django] Carefully explain the escape route if you really want to use the table of another application
Let's summarize what you want to do.
What to do if you get `locale.Error: unsupported locale setting` when getting the day of the week from a date in Python
When generating a large number of graphs with matplotlib, I do not want to display the graph on the screen (jupyter environment)
If you want a singleton in python, think of the module as a singleton
[Python] If you want to draw a scatter plot of multiple clusters
What to do if you get a TypeError with numpy min, max
If you want to switch the execution user in the middle of a Fabric task, settings context manager
I want to use complicated four arithmetic operations in the IF statement of the Django template! → Use a custom template
I want to solve the problem of memory leak when outputting a large number of images with Matplotlib
I want to easily create a Noise Model
Upload a large number of images to Wordpress
What to do if you can't pipenv shell
I want to visualize the transfer status of the 2020 J League, what should I do?
What to do if you get a "No versions found" error in pipenv
One-liner to create a large number of test files at once on Linux
How to count the number of elements in Django and output to a template
Test the number of times you have thrown a query (sql) in django
What to do if Django can't load an image from a static folder
What you want to memorize with the basic "string manipulation" grammar of python
What to do if a version error occurs in the selenium Chrome driver
What to do if (base) is displayed at the beginning of the Mac terminal
What to do when you want to receive files from a Windows client remotely
I tried to create a model with the sample of Amazon SageMaker Autopilot
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
What to do if you can't pip install mysqlclient
No module named What to do if you get'libs.resources'
What to do if the Microsoft Store opens even if you run python on Windows
ModuleNotFoundError: No module What to do if you get'tensorflow.contrib'
What happens if you graph the number of views and ratings/comments of the video of "Flag-chan!" [Python] [Graph]
What to do if you get a memory error when converting from PySparkDataFrame to PandasDataFrame
What to do if pvcreate produces a lot of WARNING and cannot be created
What to do if you get "(35,'SSL connect error')" in pycurl (one of them)
Links to do what you want with Sublime Text
What to do if the progress bar is not displayed in tqdm of python
What to do if a UnicodeDecodeError occurs in pip
I want to create a lunch database [EP1] Django study for the first time
I want to create a lunch database [EP1-4] Django study for the first time
What to do if you don't want to use Japanese column names when using ortoolpy.logistics_network
What is the last programming language you learn in your life? (If you want to catch up with a club with a lifetime salary of 300 million yen)
What to do if you get the error ʻERR_FEATURE_UNAVAILABLE_ON_PLATFORM` when using ts-node-dev on Linux
What to do if you can't hit the arrow keys in the Python interactive console
What to do if you have corrected the mistake in the IP address of the zone file but cannot connect to the DNS server
[* CentOS 6.10] What to do if you cannot add the IUS Community Project repository on CentOS 6.5 (VirtualBox)
How to create a record by pasting a relation to the inheriting source Model in the Model inherited by Django
What to do if you get a Cannot retrieve metalink for repository error in yum
What to do if you get an Undefined error:'Module_six_moves_urllib_parse' object has no attribute'urlencode' on MacOS
[Python] If you suddenly want to create an inquiry form
What to do if the package dependency cannot be repaired
What to do if you are addicted to Windows character code
What to do if pip gives a DistributionError in Homebrew
The story of a Django model field disappearing from a class
I made a function to check the model of DCGAN