Dealing with import of foreignKeys in django-import-export

 ̄綄美尐妖づ 提交于 2019-11-29 05:20:24
HydrUra

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!