Created
December 1, 2023 15:31
-
-
Save redsymbol/bc558cc2c7cf4f70966a19decd022de2 to your computer and use it in GitHub Desktop.
Export Django model as CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Usage: | |
export DJANGO_SETTINGS_MODULE=project_name.settings | |
djcsv.py someapp.models.SomeModel > output.csv | |
Run "djenv.py -h" for full help. | |
''' | |
import importlib | |
import argparse | |
import csv | |
import sys | |
import django | |
django.setup() | |
DEFAULT_COUNT = 1000 | |
def get_args(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('dotted_path') | |
parser.add_argument('-c', '--count', default=DEFAULT_COUNT, type=int, | |
help='Export the most recent COUNT records (highest PKs)') | |
parser.add_argument('--all', action='store_true', default=False, | |
help='Export all records. Overrides --count') | |
return parser.parse_args() | |
def load_model_class(dotted_path): | |
split_pos = dotted_path.rfind('.') | |
assert split_pos > 0, dotted_path | |
module_name, model_class_name = dotted_path[:split_pos], dotted_path[split_pos+1:] | |
module = importlib.import_module(module_name) | |
model_class = getattr(module, model_class_name) | |
return model_class | |
def field_names(model_class): | |
return [ | |
field.name | |
for field in | |
model_class._meta.get_fields() | |
] | |
if __name__ == '__main__': | |
args = get_args() | |
model_class = load_model_class(args.dotted_path) | |
fields = field_names(model_class) | |
csv_out = csv.DictWriter(sys.stdout, fields) | |
csv_out.writeheader() | |
if args.all: | |
records = model_class.objects.all() | |
else: | |
records = model_class.objects.order_by('-pk')[:args.count] | |
for record in records: | |
csv_out.writerow({ | |
field: getattr(record, field) | |
for field in fields | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment