1

I to try run this code:

# -*- coding: utf-8 -*-

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    def handle(self, *args, **options):

        from blogs.models import Blog, Post
        from sitename.settings import DEFAULT_CHARSET

        for blog in Blog.objects.all().using('old'):
            try:
                Blog.objects.get(old_id=blog.id)
                continue
            except:
                pass
            new_blog = Blog(
                name =      blog.name,
                description=blog.description,
                old_id =   blog.id
            )
            new_blog.save()

But i have exception:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)

I googled this problem and find this solution:

name = blog.name.encode('ascii','ignore')

The result was upset: All Russian symbols have been removed.

"Пост номер 15-14" => "15-14"

How shall I copy the data correctly?

4

1 回答 1

1

我想,您对一个或两个数据库的字符集有疑问,您应该检查从旧数据库中获得的编码以及新数据库中的编码。

你的循环看起来很奇怪,Django 有一个很好的函数get_or_create方法 on QuerySet,所以有很好的版本:

for blog in Blog.objects.all().using('old'):
    Blog.objects.get_or_create(old_id=blog.id, defaults={'name': blog.name,
                                                         'description': blog.description})
于 2016-06-13T22:08:32.217 回答