迁移错误__fake__。不存在:标签匹配查询不存在

时间:2018-10-19 13:11:50

标签: python django python-3.x

迁移

def add_startup_data(apps, schema_editor):
    Startup = apps.get_model('organiser', 'Startup')
    Tag = apps.get_model('organiser', 'Tag')
    for startup in STARTUPS:
        startup_object = Startup.objects.create(
            name=startup['name'],
            slug=startup['slug'],
            contact=startup['contact'],
            description=startup['description'],
            founded_date=startup['founded_date'],
            website=startup['website'])
        for tag_slug in startup['tags']:
            var=Tag.objects.get(slug=tag_slug)
            startup_object.tags.add(var)

def remove_startup_data(apps, schema_editor):
    Startup = apps.get_model(
        'organiser', 'Startup')
    for startup in STARTUPS:
        startup_object = Startup.objects.get(
            slug=startup['slug'])
        startup_object.delete()
class Migration(migrations.Migration):
     dependencies = [
        ('organiser', '0002_tag_data'),
    ]
     operations = [
        migrations.RunPython(
            add_startup_data,
            remove_startup_data)
    ]

我收到以下错误:

self.model._meta.object_name 
__fake__.DoesNotExist: Tag matching query does not exist.

我似乎无法修复它。我尝试过get_object_or_404,但这只会导致另一个错误

1 个答案:

答案 0 :(得分:1)

捕获Tag.DoesNotExist异常,如下所示:

    for tag_slug in startup['tags']:
        try:
            var=Tag.objects.get(slug=tag_slug)
            startup_object.tags.add(var)
        except Tag.DoesNotExist:
            pass

get_object_or_404快捷方式捕获异常并引发Http404。在视图中执行此操作时,这会导致Django显示404错误页面。在迁移中使用get_object_or_404是没有意义的,因为它不是视图。