fix_homonym.py 777 Bytes
#-*- coding:utf-8 -*-

from django.core.management.base import BaseCommand
from django.db.models import Count
from common.util import no_history
from dictionary.models import Lexeme


class Command(BaseCommand):
    args = 'none'
    help = 'fixes homonym numbers'

    def handle(self, **options):
        fix_homonym()


def fix_homonym():
    no_history()
    homonyms = (
        Lexeme.objects.values('entry', 'part_of_speech')
        .annotate(count=Count('pk')).filter(count__gt=1))
    for homonym in homonyms:
        lexemes = Lexeme.objects.filter(
            entry=homonym['entry'],
            part_of_speech=homonym['part_of_speech']).order_by('pk')
        for i, lexeme in enumerate(lexemes, 1):
            lexeme.homonym_number = i
            lexeme.save()