コード例 #1
0
def create_reporters():
    from apps.contacts.models import Contact, CommunicationChannel, ChannelConnection
    from apps.reporters.models import Reporter, PersistantBackend, PersistantConnection

    # add reporter_id, allowing null values for now
    cursor = connection.cursor()
    cursor.execute("ALTER TABLE `contacts_contact` ADD COLUMN `reporter_id` INT(11) DEFAULT NULL AFTER `node_ptr_id`;")
    cursor.execute("ALTER TABLE `contacts_contact` ADD CONSTRAINT `reporter_id_refs_id_32f59ca5` FOREIGN KEY (`reporter_id`) REFERENCES `reporters_reporter` (`id`);")
    cursor.execute("ALTER TABLE `contacts_contact` ADD CONSTRAINT UNIQUE `reporter_id_unique` (`reporter_id`);")

    all_contacts = Contact.objects.all()
    for contact in all_contacts:
        print "processing contact %s" % contact.get_signature()
        
        # NEW reporter models
        rep = Reporter()
        rep.alias = contact.unique_id
        rep.first_name = contact.given_name
        rep.last_name = contact.family_name
        rep.language = contact._locale
        rep.save()
        
        contact.reporter = rep
        contact.save()
        
        # check
        conns = contact.channel_connections.all()
        conns_count = conns.count()
        if conns_count==0:
            print "%s has no connections" % (contact.get_signature())
        elif conns_count>1:
            print "%s has more than one connections" % (contact.get_signature())

        # create various connection objects
        for conn in conns:
            new_conn = PersistantConnection()
            new_conn.identity = conn.user_identifier
            new_conn.backend = PersistantBackend.objects.get(slug=conn.communication_channel.backend_slug)
            new_conn.reporter = rep
            new_conn.save()
            conn.delete()
                   
    # check
    unassociated_contacts = Contact.objects.filter(reporter=None)
    if len(unassociated_contacts)>0:
        print "PROBLEMS WITH GENERATING REPORTERS!"
        print "UNASSOCIATED: "
        for con in unassociated_contacts:
            print " contact id: %s\n" % con.id 

    # check
    contact_count = all_contacts.count()
    reporter_count = Reporter.objects.all().count()
    if contact_count != reporter_count:
        raise Exception("Mismatch between contact and reporter count! %s %s" \
                        % (contact_count, reporter_count))