# coding=utf-8

from django.core.management import BaseCommand
from django.db.models import Count

from api.models import TopicReplyVote, TopicReply


class Command(BaseCommand):
    """
    NOTE:
        更新topicreply中的点赞like_num字段
    """

    def handle(self, *args, **kwargs):
        # update topicreply like num
        """
        steps:
          - get all votes from topicreplyvote
          - update topicreply.like_num
        """
        trs = TopicReplyVote.objects.values('topic_reply').annotate(vote_count=Count('topic_reply'))
        for tr in trs:
            try:
                print tr['topic_reply'], ' ', tr['vote_count']
                _tr = TopicReply.objects.get(pk=tr['topic_reply'])
                _tr.like_num = tr['vote_count']
                _tr.save()
            except Exception as e:
                print e
