get_as_csv.py 1.41 KB
# -*- coding:utf-8 -*-

import codecs
import datetime
import os

from django.core.management.base import BaseCommand

from settings import PROJECT_PATH
from webapp.models import Meaning

CSV_PATH = os.path.join(PROJECT_PATH, 'data', 'periphraser_%s.csv' % datetime.datetime.now().strftime('%Y%m%d'))
LABELS = [u'znaczenie',
          u'wyrażenie',
          u'wyrażenie pochodne',
          u'źródło',
          u'kategoria',
          u'wikilink']


class Command(BaseCommand):
    help = 'Get database as csv.'

    def handle(self, *args, **options):
        write_csv()


def write_csv():
    csv_file = codecs.open(CSV_PATH, 'wt', 'utf-8')
    csv_file.write(u'%s\n' % u'\t'.join(LABELS))
    for meaning in Meaning.objects.order_by('id'):
        print meaning.id
        for expr in meaning.expressions.filter(main_expression=None).order_by('text'):
            main_mention = ''
            if expr.mentions.exists():
                main_mention = expr.mentions.all()[0].text
            csv_file.write(u'%d\t%s\t%s\t%s\t%s\t%s\n' % (meaning.id,
                                                          expr.text,
                                                          main_mention,
                                                          expr.sources.all()[0].name,
                                                          meaning.category.name,
                                                          meaning.wikilink))