Skip to content

Instantly share code, notes, and snippets.

@vinyll
Created February 2, 2018 16:30
Show Gist options
  • Save vinyll/3dccfd064305c32e000746286e7ad434 to your computer and use it in GitHub Desktop.
Save vinyll/3dccfd064305c32e000746286e7ad434 to your computer and use it in GitHub Desktop.
import os
import sys
from pathlib2 import Path
import argparse
root_dir = Path(__file__).absolute().parent.parent
sys.path.append(str(root_dir))
sys.path.append(str(root_dir / 'apps'))
sys.path.append(str(root_dir / 'libs'))
parser = argparse.ArgumentParser()
parser.add_argument("--settings", default='settings.local', help="settings files")
parser.add_argument("--limit", default=99999, help="max number of articles")
args = parser.parse_args()
os.environ.setdefault('DJANGO_SETTINGS_MODULE', args.settings)
# Call these for avoiding import order error!
import cacheops
import m2m_custom_through_signals
# --- #
import json
from django.core import serializers
from editorials.models import base
from django.core.exceptions import ObjectDoesNotExist
editorials = base.Base.objects.select_related('article', 'writers', 'gallery', 'video').order_by('created_at').all()[:args.limit]
def to_object(model):
return json.loads(serializers.serialize('json', [model]))[0]
output = []
for e in editorials:
obj = to_object(e)
try:
obj['article'] = to_object(e.article)
except ObjectDoesNotExist:
pass
try:
obj['groups'] = [to_object(g) for g in e.group_set.all()]
except ObjectDoesNotExist:
pass
try:
obj['video'] = to_object(e.video)
except ObjectDoesNotExist:
pass
try:
obj['gallery'] = to_object(e.gallery)
obj['gallery']['images'] = [to_object(i) for i in e.gallery.galleryitem_set.all()]
except ObjectDoesNotExist:
pass
output.append(obj)
print(json.dumps(output, indent=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment