# coding=utf-8

from django.core.management import BaseCommand

from django.db import models
from django.db.models import Count
from django.contrib.auth.models import User
from django.utils import timezone

from api.models import *


class Command(BaseCommand):
    """if order related multiple diaries, delete the link, just keep one.
    """
    def handle(self, *args, **options):
        diaries = Diary.objects.filter(order__isnull=False)

        for o in diaries.raw('select id, order_id, count(*) c from api_diary group by order_id having(c>1);'):
            if not o.order_id: continue

            ds = Diary.objects.filter(order_id=o.order_id)

            found = False
            for d in ds:
                print d.id, d.order_id

                if found == True:
                    d.order_id = None
                    d.save()

                found = True
