add_missing_heads.py 882 Bytes
from django.core.management.base import BaseCommand

from webapp.models import Meaning, Segment


class Command(BaseCommand):
    help = 'Add missing heads to single segment expressions.'

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


def add_missing_heads():
    for meaning in Meaning.objects.all():
        expressions = meaning.expressions.all()
        for expression in expressions:
            if missing_head(expression) and expression.segments.count() == 1:
                head = expression.segments.all()[0]
                print 'adding head:\t', meaning, '---->', expression, '---->', head
                head.is_head = True
                head.save()


def missing_head(expression):
    is_missing = False
    try:
        expression.segments.get(is_head=True)
    except Segment.DoesNotExist:
        is_missing = True
    return is_missing