处理django-import-export中的foreignKeys导入 [英] Dealing with import of foreignKeys in django-import-export

查看:2773
本文介绍了处理django-import-export中的foreignKeys导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白django-import-export模块如何处理ForeignKeys。
这是一个简单的例子:
models.py

  class TFamilies(models.Model):
id_fam = models.AutoField(primary_key = True,unique = True)
name_fam = models.CharField(max_length = 1024,blank = True,verbose_name ='Famille')


class TGenus(models.Model):
id_genus = models.AutoField(primary_key = True,unique = True)
name_genus = models.CharField(max_length = 1024,verbose_name ='nom de genre' )
id_fam = models.ForeignKey(TFamilies,null = True,db_column ='id_fam',blank = True,verbose_name ='Famille')

我想允许人们添加属与家人相关联的人!一个CSV / XLS只有name_genus和name_fam ...(和id留空)。



大部分时间里,DB已经存在于DB中,Django juste必须找到右侧编号...



admin.py

  class TGenusResource (resource.ModelResource):

name_fam = fields.Field(widget = widgets.ForeignKeyWidget(TFamilies,'name_fam'))

class Meta:
model = TGenus
import_id_fields = ['id_genus']


class TGenusAdmin(ImportExportActionModelAdmin):
form = TGenusAdminForm
resource_class = TGenusResource
pass

此配置导致导入界面中的错误:

 行号:1  - 'NoneType'对象没有属性'name_fam'
追溯(最近的最后一次调用):
文件/ ..... ./lib/python2.7/site-packages/import_export/resources.py,第348行,import_data
row_result.object_repr = forc e_text(instance)
文件....... / lib / python2.7 / site-packages / django / utils / encoding.py,第85行,在force_text
s = six.text_type (s)
AttributeError:'NoneType'对象没有属性'name_fam'

不明白...
我也试过回答: django-import-export资源定义为foreignkey字段?
和类似于:
使用django-import-export进行django迁移的外键



我必须使用 before_import 以找到自己比赛?

解决方案

我想,你必须找到自己的比赛!改变tablib数据集中的值是不可能的,所以你必须将条目进行更改,并将它们放回到新行中,然后删除旧的值。



我的excel模板包含列 id_genus (空), name_genus id_fam 以家庭名称填写!



对于任何降落在这里的人,我发布我的方式:

  def before_import(self,dataset,dry_run):

在显示给用户
之前对数据集进行标准更正

i = 0
last = dataset.height - 1

#为所有行,搜索给定的家庭ID,并在底部添加一个新行,然后删除第一个
,而i < = last:
#检查属性是否存在于DB
if(TGenus.objects.filter(name_genus = dataset.get_col(2)[0] .capitalize())):
id_genus = TGenus.objects.filter(name_genus = dataset.get_col(2)[0] .capitalize())[0] .id_genus
else:
id_genus =''
#检查是否家族存在于DB
try:
TFamilies.objects.get(name_fam = dataset.get_col(2)[0] .capitalize())
除了TFamilies.DoesNotEx ist:
raise异常(Family not in DB!)
除了TFamilies.MultipleObjectsReturned:
pass

#使用filter而不是get为了防止重复的值,在所有情况下选择第一个
dataset.rpush((id_genus,
dataset.get_col(1)[0],
TFamilies.objects.filter(name_fam = dataset .get_col(2)[0] .capitalize())[0] .id_fam))
dataset.lpop()
i = i + 1
pre>

我的django管理员可以由非sys-admin使用,所以他们可以并复制不在数据库中的属或者家族...
如果有人有一个想法来处理错误更好,我想读它!
此外,我想保留家庭的名字在预览,不仅她的id ...如果你知道如何,我已经发布了另一个问题:是否可以在django import-export中自定义预览模板?


I don't understand how django-import-export module deals with ForeignKeys. Here is a simple exemple : models.py

class TFamilies(models.Model):
    id_fam = models.AutoField(primary_key=True, unique=True)
    name_fam = models.CharField(max_length=1024, blank=True,verbose_name='Famille')


class TGenus(models.Model):
    id_genus = models.AutoField(primary_key=True, unique=True)
    name_genus = models.CharField(max_length=1024,verbose_name='nom de genre')
    id_fam = models.ForeignKey(TFamilies, null=True, db_column='id_fam', blank=True, verbose_name='Famille')

I would like to allow people adding genus with family associated ! A CSV/XLS with only name_genus and name_fam... (and id left blank).

Family already exist in DB most of the time, Django juste have to find the right id number...

admin.py

class TGenusResource(resources.ModelResource):

    name_fam = fields.Field(widget=widgets.ForeignKeyWidget(TFamilies, 'name_fam'))

    class Meta:
        model = TGenus
        import_id_fields = ['id_genus']


class TGenusAdmin(ImportExportActionModelAdmin):
    form = TGenusAdminForm
    resource_class = TGenusResource
    pass

This configuration lead to error in import interface :

Line number: 1 - 'NoneType' object has no attribute 'name_fam'
Traceback (most recent call last):
File "/....../lib/python2.7/site-packages/import_export/resources.py", line 348, in import_data
row_result.object_repr = force_text(instance)
File "......./lib/python2.7/site-packages/django/utils/encoding.py", line 85, in force_text
s = six.text_type(s)
AttributeError: 'NoneType' object has no attribute 'name_fam'

I don't understand... I also tried answer there : django-import-export resource definition for foreignkey field? and sort of like there : Foreign Key in django migration using django-import-export

Do I have to use before_import to find myself the match ?

解决方案

I figured out that you have to find yourself the match ! It's impossible to alterate values in a tablib dataset so you have to take entries make changes and put them back in a new line then erase the old one.

My excel template contains columns id_genus (empty), name_genus and id_fam filled by the name of the family !

For anyone who landed here I post my way :

def before_import(self, dataset, dry_run):
        """
        Make standard corrections to the dataset before displaying to user
        """

        i = 0
        last = dataset.height - 1

        # for all lines, search for id of family given and add a new line at the bottom with it then delete the first one
        while i <= last:
            # Check if the Genus exist in DB
            if (TGenus.objects.filter(name_genus=dataset.get_col(2)[0].capitalize())):
                id_genus = TGenus.objects.filter(name_genus=dataset.get_col(2)[0].capitalize())[0].id_genus
            else :
                id_genus = ''
            # Check if the family exists in DB
            try:
                TFamilies.objects.get(name_fam=dataset.get_col(2)[0].capitalize())
            except TFamilies.DoesNotExist:
                raise Exception("Family not in DB !")                   
            except TFamilies.MultipleObjectsReturned:
                pass

            # use of "filter" instead of "get" to prevent duplicate values, select the first one in all cases
            dataset.rpush((id_genus,
                dataset.get_col(1)[0],
                TFamilies.objects.filter(name_fam=dataset.get_col(2)[0].capitalize())[0].id_fam))
            dataset.lpop()
            i = i + 1

My django admin can be used by non sys-admin so, they can and duplicate genus or families that aren't in DB... If someone have an idea to deal with errors better, I would like to read it ! Also, I would like to keep the name of the family in the preview, not only her id... If you know how, I have posted another question about that : Is-it possible to customize the template of preview in django import-export?

这篇关于处理django-import-export中的foreignKeys导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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