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)