Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django call';id';应为数字,但得到字符串_Python_Django_Django Admin_Django Import Export - Fatal编程技术网

Python Django call';id';应为数字,但得到字符串

Python Django call';id';应为数字,但得到字符串,python,django,django-admin,django-import-export,Python,Django,Django Admin,Django Import Export,Django导入导出库出现Django错误 我想通过django admin将数据从excel导入db。我使用django导入导出,但我得到了字段“id”,该字段应该是一个数字,但得到了“HPI” Excel文件包含 我找到了答案,我必须添加exclude=('id',),但它并没有帮助。我也做了迁移,也没什么帮助。 如何修复它并能够通过django admin将6列数据从excel导入db models.py from django_mysql.models import JSO

Django导入导出库出现Django错误

我想通过django admin将数据从excel导入db。我使用django导入导出,但我得到了字段“id”,该字段应该是一个数字,但得到了“HPI”

Excel文件包含

我找到了答案,我必须添加exclude=('id',),但它并没有帮助。我也做了迁移,也没什么帮助。 如何修复它并能够通过django admin将6列数据从excel导入db

models.py


    from django_mysql.models import JSONField, Model
    from django.db import models



    class Category(Model):
        title = models.CharField(max_length=100)

        class Meta:
            ordering = ('-id',)
            verbose_name = 'Category'
            verbose_name_plural = 'Categories'

        def __str__(self):
            return self.title


    class Tag(Model):
        title = models.CharField(max_length=100)

        class Meta:
            ordering = ('-id',)

        def __str__(self):
            return self.title


    class Type(Model):
        title = models.CharField(max_length=100)

        class Meta:
            ordering = ('-id',)
            verbose_name = 'Type'
            verbose_name_plural = 'Types'

        def __str__(self):
            return self.title


    class Macro(Model):
        type = models.ForeignKey(
            Type,
            max_length=100,
            null=True,
            blank=True,
            on_delete=models.SET_NULL)
        tags = models.ManyToManyField(Tag, blank=True)
        category = models.ForeignKey(
            Category, null=True, blank=True, on_delete=models.SET_NULL)
        abbreviation = models.CharField(max_length=100, unique=True)
        title = models.CharField(max_length=100, verbose_name='Title')
        content = models.TextField(max_length=1000, null=True, blank=True)

        class Meta:
            ordering = ('-id',)

        def __str__(self):
            return self.title

管理员


    from django.contrib import admin

    from import_export import resources
    from import_export.admin import ImportExportModelAdmin

    from .models import Category, Tag, Type, Macro


    class MacroResource(resources.ModelResource):

        class Meta:
            model = Macro
            skip_unchanged = True
            report_skipped = True
            exclude = ('id', )
            export_order = ('type', 'tags', 'category', 'abbreviation', 'title', 'content')


    @admin.register(Macro)
    class MacroAdmin(ImportExportModelAdmin):
        resource_class = MacroResource
        list_display = ('id', 'type', 'tags_list', 'category', 'abbreviation', 'title', 'content')
        search_fields = ('title', 'category__title', 'type__title', 'abbreviation', 'content', )

        def tags_list(self, obj):
            tags = [t for t in obj.tags.all()]
            return ' '.join(str(tags)) if tags else '-'


    @admin.register(Category)
    class CategoryAdmin(admin.ModelAdmin):
        list_display = ('id', 'title')


    @admin.register(Tag)
    class TagAdmin(admin.ModelAdmin):
        list_display = ('id', 'title')

        def __str__(self):
            return self.title


    @admin.register(Type)
    class TypeAdmin(admin.ModelAdmin):
        list_display = ('id', 'title')


Django导入导出要求第一列为
id

如果这些是新对象,只需将
id
列留空即可。否则,将对象的数据库id放在该字段中

如果您无法修改文件,或者不想修改,并且您将始终向数据库添加新行(而不是修改现有行),则可以在资源类中动态创建id字段,方法是在导入之前覆盖方法
,并强制
获取实例
始终返回
False

class MacroResource(resources.ModelResource):

    def before_import(self, dataset, using_transactions, dry_run, **kwargs):
        dataset.insert_col(0, col=["",]*dataset.height, header="id")

    def get_instance(self, instance_loader, row):
        return False

    class Meta:
        model = Macro
        skip_unchanged = True
        report_skipped = True
        export_order = ('type', 'tags', 'category', 'abbreviation', 'title', 'content')

问题在于ForeignKey和数据库模型的许多字段。所以django导入导出库需要获取此字段的小部件

更多信息请点击此处:

解决方案: 管理员


        class MacroResource(resources.ModelResource):

            type = fields.Field(
                column_name='type',
                attribute='type',
                widget=ForeignKeyWidget(Type, 'title'))

            category = fields.Field(
                column_name='category',
                attribute='category',
                widget=ForeignKeyWidget(Category, 'title'))

            tags = fields.Field(
                column_name='tags',
                attribute='tags',
                widget=ManyToManyWidget(Tag, field='title'))

            class Meta:
                model = Macro
                skip_unchanged = True
                report_skipped = True
                exclude = ('id', )
                import_id_fields = ('title',)

                fields = ('type', 'tags', 'category', 'abbreviation', 'title', 'content')
而不是


        class MacroResource(resources.ModelResource):

            class Meta:
                model = Macro
                skip_unchanged = True
                report_skipped = True
                exclude = ('id', )
                export_order = ('type', 'tags', 'category', 'abbreviation', 'title', 'content')



在模型中使用外键的属性,
您需要指定父模型的id,而不是xlsx/csv文件中的值。

BTW,您是如何从导入导出中获得如此好的错误报告的?我只得到一个堆栈跟踪列表。@GregKaleka我不知道,这只是管理员仪表板中的错误报告谢谢,但我得到了和错误“在_import()接受3个位置参数但给出4个之前”。我删除了dry_run,得到了“before_import()接受2个位置参数,但给出了4个”。您可以帮忙吗?我在导入之前添加了使用\u事务,但是得到了一个类似的错误“一些行无法验证,请尽可能更正数据中的这些错误,然后使用上面的表单重新加载。”以及“字段“id”需要一个数字,但得到了“HPI”。“啊,是的,抱歉-
使用_事务
不需要在呼叫签名中。至于仍然得到错误-我认为我们还需要重写
get\u instance
方法。我更新了我的答案。如果这不起作用,您可以深入堆栈跟踪并查看错误的来源吗?不幸的是,这没有帮助。控制台中没有错误,只有“POST/admin/macros/macros/import/HTTP/1.1”200 15554。我在管理仪表板中看到一条错误消息,如“某些行无法验证,请尽可能更正数据中的这些错误,然后使用上面的表单重新加载。”和“键入字段'id'需要一个数字,但得到'HPI'您能否详细说明如何在ForeignKeyWidget中使用的属性中指定父模型的id?这对我会有帮助的。谢谢,因为我们知道每个对象都有一个唯一的id(主键)。因此,我们需要指定该对象的id,而不是该对象的名称。如果有两个OBEJCT具有相同的名称,为了避免该错误,我们在表中使用它们的主键/唯一id。希望这是有帮助的。