Django导入/导出到多个模型(外键) [英] Django Import/Export to multiple Models (foreignkey)

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

问题描述

这个问题已经被问了好几次了,但是没有一个解决方案对我有用.

This has been asked several times- but none of the solutions worked for me.

下面的代码可以正常工作(因为没有错误),但是看不到将 new 数据导入到外键类的任何内容.仅在外键中已经存在的情况下,才会导入数据.

The code below works (in that there are no errors) but it does not see anything to import new data to the foreign key class. It will only import data if it already exists 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)

推荐答案

尝试

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

我建议您命名模型字段uncapitalized

I suggest you name model field uncapitalized

很难理解您的真正要求.

It's hard to understand what you are really asking.

如果您要说的是想创建外键对象并用excel数据填充外对象的属性"

If what you are saying is that "Want to create foreign key objects and fill the foreign object's attribute with the excel data"

我认为您首先需要创建异物并将其与其他模型相关联,这意味着您需要在ModelResource类中覆盖或定义一个函数,然后从管理员那里调用它.

I think you need to do first create the foreign object and relate it to the other model which means, you would need to override or define a function in your ModelResource class and have it called from your admin.

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

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