0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Django models to DataFrame to csv

Last updated at Posted at 2022-02-08

from datetime import datetime
import numpy

from django.core.management import BaseCommand
from django.db.models.fields import DateTimeField, BooleanField

from model import YourModel

import pandas as pd


# Usage
ExportModel(YourModel, ForeignKey)


class ExportModel:

    def __init__(self, model, key):
        self.target_model = model
        self.key = key
        self.target_key_value = {"key":key}

    def exec(self):
        if self._target_table_check_exists_key():
            self._target_model_export_data()

    def _target_table_check_exists_key(self):
        self.target_model_filterd_key_qs = self.target_model.objects.filter(**self.target_key_value)
        if len(self.target_model_filterd_key_qs) > 0:
            return True
        else:
            return False

    def _target_model_export_data(self):
        df = pd.DataFrame.from_records(self.target_model_filterd_key_qs.values())

        for col in self.target_model._meta.fields:
            if col.__class__ == DateTimeField:
                df[col.name] = pd.to_datetime(df[col.name])
                df[col.name] = df[col.name].dt.strftime('%Y-%m-%d %H:%M:%S')

            if col.__class__ == BooleanField:
                df[col.name] = df[col.name].replace(False, "0")
                df[col.name] = df[col.name].replace(True, "1")

        # ほとんどのFiledsのNoneはNAで抽出できる
        df = df.replace(pd.NA, "NULL")
        # DateTimeFieldsのNullはNaN
        df = df.replace(numpy.NaN, "NULL")

        csv_file_name = f"""{self.key}_{self.target_model.__name__}_deleted_{datetime.now().strftime("%Y-%m-%d_%H:%M")}.csv"""
        df.to_csv(csv_file_name, index=False)

概要

  • DjangoのモデルからDataFrameに変換して、Sequelとかにそのまま読み込ませれるような形式でCSVに出力するサンプルコードです。

学び

  • 多少(1~2割ぐらい)修正していますが、実際に書いたコードをほぼそのまま載せています。
  • 手前味噌ですが、ある程度良いコード?は抽象化されているからそのまま載せてもほぼほぼ問題ない可能性が高いのかなとか思ったりしました。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?