update_entries.py 1.83 KB
from django.core.management.base import BaseCommand

from webapp.models import Entry, Expression


class Command(BaseCommand):
    help = 'Update Entry objects.'

    def handle(self, *args, **options):
        remove_entries()
        add_entries()


def remove_entries():
    Entry.objects.all().delete()


def add_entries():

    try:
        catchwords = Expression.objects.filter(is_catchword=True,
                                               link__source__low_quality=False).order_by('text')
        for expr in catchwords:
            if (expr.DDG_entry_responses >= expr.link.source.min_DDG_entry_responses and
                        expr.DDG_responses >= expr.link.source.min_DDG_expression_responses and
                        meaning_ok(expr.meaning)):

                print ('Adding catchword: ' + expr.text)
                entry, created = Entry.objects.get_or_create(name=expr.text)

                domains = expr.meaning.domains.all()
                meaning = expr.meaning
                source = expr.link.source

                entry.domains.add(*domains)
                entry.meanings.add(meaning)
                entry.sources.add(source)
    finally:
        for entry in Entry.objects.order_by('name'):

            if not entry.sources.filter(protected=False).exists():
                print ('Protected entry: ' + entry.name)
                entry.protected = True
                entry.save()

            if not entry.sources.filter(low_quality=False).exists():
                print ('Removing entry: ' + entry.name)
                entry.delete()


def meaning_ok(meaning):
    correct_expressions = 0
    for expr in meaning.expressions.all():
        if expr.DDG_responses >= expr.link.source.min_DDG_expression_responses:
            correct_expressions += 1
        if correct_expressions > 1:
            return True
    return False