for i in cursor.fetchall(): """ Seleccionamos los tags, hay que agregarlos de la forma (tag1, tag2, tag3) como string al campo tags de blog_post """ tags_cursor = conn.cursor() # no se si es necesario, pero por si las moscas ;P tags_cursor.execute ("""SELECT * FROM posts_tags, tags WHERE posts_tags.post_id='%s' AND posts_tags.tag_id=tags.id""" % i[0]) thetags = ", ".join([str((tag[4])) for tag in tags_cursor.fetchall()]) tags_cursor.close() try: cursor2.execute("INSERT INTO blog_post \ (id, title, slug, text, hits, creation_date, tags, status, user_id) \ VALUES (%s, '%s', '%s', '%s', %s, '%s', '%s', %s, 1);" % (i[0], unicode(i[1], 'iso-8859-15').encode('utf-8'), i[2], unicode(i[3], 'iso-8859-15').encode('utf-8'), i[4], i[5], thetags, i[6])) post_newid = cursor2.lastrowid print "INSERT INTO blog_post \ (id, title, slug, text, hits, creation_date, tags, status, user_id) \ VALUES (%s, '%s', '%s', '%s', %s, '%s', '%s', %s, 1);" % (i[0], unicode(i[1], 'iso-8859-15').encode('utf-8'), i[2], unicode(i[3], 'iso-8859-15').encode('utf-8'), i[4], i[5], thetags, i[6]) except MySQLdb.IntegrityError, message: print "Duped!" pass else: """ Comprobamos si el tag existe en tagging_tag(id, name). Si existe nos quedamos con su id, si no existe lo agregamos y nos quedamos con su id """ tags_cursor = conn.cursor() # no se si es necesario, pero por si las moscas ;P tags_cursor.execute ("""SELECT * FROM posts_tags, tags WHERE posts_tags.post_id='%s' AND posts_tags.tag_id=tags.id""" % i[0]) for tag in tags_cursor.fetchall(): tags_cursor2 = conn2.cursor() tags_cursor2.execute("SELECT id FROM tagging_tag WHERE name='%s'" % (unicode(tag[3], 'iso-8859-15').encode('utf-8'))) row = tags_cursor2.fetchone() if not row: tags_cursor3 = conn2.cursor() tags_cursor3.execute("INSERT INTO tagging_tag (name) VALUES ('%s')" % (unicode(tag[3], 'iso-8859-15').encode('utf-8'))) myid = tags_cursor3.lastrowid else: myid = row[0] """ Agregamos el elemento a tagging_taggeditem(id, tag_id, object_id, content_type_id). Content_type_id=11, es una fk de django_content_type y el 11 es el contenido tipo Post """ cursor3 = conn2.cursor() cursor3.execute("""INSERT INTO tagging_taggeditem (tag_id, object_id, content_type_id) VALUES (%s, %s, 11)""" % (myid, post_newid)) print ("""INSERT INTO tagging_taggeditem (tag_id, object_id, content_type_id) VALUES (%s, %s, 11)""" % (myid, post_newid)) cursor.close () conn.close () conn2.commit() cursor2.close () conn2.close ()