Django导入和导出foriegn键模型中的新值 [英] Django import-export new values in foriegn key model

查看:127
本文介绍了Django导入和导出foriegn键模型中的新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django进出口库存储数据.效果很好,除了无法导入外键中不存在的对象.

I'm using the django import-export library to data. It works well except I cannot get it to import objects which don't already exist in the foreign key.

如果外键模型中存在对象(csv中的值),则可以正常导入.

If the objects (values in the csv) exist in the foreign key model- then it imports fine.

但是,如果外键模型中不存在对象/值,则会显示不存在匹配查询",并且不会导入数据.

But if the objects/values don't exist in the foreign key model- it says "matching query does not exist" and will not import the data.

如果外键中不存在新对象,如何告诉它将新对象添加到外键模型中?

How can I tell it to add new object to the foreign key model if they don't exist in the foreign key?

Models.py代码段

class Store(models.Model):

    store_name = models.CharField(max_length=30)
    def __unicode__(self):
        return self.store_name
    #etc

class Product(models.Model):

    Store = models.ForeignKey(Store)
    Category = models.ForeignKey(Category)
    first_name = models.CharField(max_length=30)
    second_name = models.CharField(max_length=30)
...

Admin.py代码段

admin.site.register(Category)
admin.site.register(Store)

class ProductResource(resources.ModelResource):

     store_name = fields.Field(column_name='store_name', attribute='Store',
                       widget=ForeignKeyWidget(Store, 'store_name'))

    def __unicode__(self):
        return self.store_name.name

    class Meta:
        model = Product
        fields = ('id', 'first_name', 'second_name','store_name')
        export_order = ('id', 'second_name', 'first_name')
        skip_unchanged = False
        report_skipped = False
        widgets = {
                'published': {'format': '%d.%m.%Y'},
                }


class ProductAdmin(ImportExportModelAdmin):
    resource_class = ProductResource
    list_display = ('first_name', 'second_name')

admin.site.register(Product, ProductAdmin)

推荐答案

提供的模型的ForeignKey可以为null:

Provided the ForeignKey of your model can be null :

MyForeignKeyName = Models.ForeignKey(<modelclass>,blank=True, null=True)

您可以添加 before_import_row()方法:

def before_import_row(self,row) :
    fieldname = 'MyForeignKeyName'
    if not( <modelclass>.objects.filter(pk=row[fieldname]).exists() ) :
        # print(row['id'],row[fieldname],'unknown key !') # console log
        row[fieldname ] = None # or something else.. *

* ..符合您的外键配置 [python None = SQL null]

*.. compliant with your foreignkey configuration [ python None = SQL null ]

我对Django有点陌生,所以也许这不是更好的方法,但这可以解决我的问题.

I'm a bit new to Django so maybe it's not the better way, but this solves my problem.

关于db_constraint = False的东西也可以添加到ForeignKey的参数中(一些信息 @stackoverflow @ django ),但是很好,我没有找到解决方法.

There's also something about db_constraint=False that can be added to ForeignKey's arguments (some info @stackoverflow and @django) but well, I did not find my way with it.

这篇关于Django导入和导出foriegn键模型中的新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆