Django-Import-Export數(shù)據(jù)導(dǎo)出導(dǎo)入插件關(guān)于外鍵的處理
前言
Django-Import-Export是一款很好用很方便的Django數(shù)據(jù)導(dǎo)出導(dǎo)入插件,可以和DjangoAdmin管理后臺完美集成,只需要少量的代碼配置即可方便實現(xiàn)你要的多種格式導(dǎo)出導(dǎo)入,關(guān)于這個插件的使用更多可以看我之前的文章:Django數(shù)據(jù)導(dǎo)入導(dǎo)出神器django-import-export使用
之前我在使用中都是專門做了一個原始數(shù)據(jù)的表來存導(dǎo)入的數(shù)據(jù),然后再對原始數(shù)據(jù)表做一些數(shù)據(jù)處理,把數(shù)據(jù)存到其他表才能真正使用這些數(shù)據(jù)。(不是很好的做法好像)
然后現(xiàn)在需要的是在已有表結(jié)構(gòu)的基礎(chǔ)上,導(dǎo)入數(shù)據(jù),而且我需要導(dǎo)入數(shù)據(jù)的這個表,里面還有幾個外鍵,這就涉及到對于外鍵的處理了。
于是在網(wǎng)上查了很久(面向Google編程),國內(nèi)的資料以參考資料的兩個文章為主,看了下類似奇技淫巧的hack方式解決的,感覺一般般,這樣hack方式不能讓我滿意,于是放棄Google,直接啃官方文檔(我好后悔為啥不一開始就啃官方文檔……)
解決方案
真正的解決方案,還得看官方文檔。
模型配置
先看看模型是怎么定義的,這里我把官方的examples放出來,我自己項目的模型字段太多了,還是看官方的比較清楚。
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Book(models.Model):
name = models.CharField('Book name', max_length=100)
author = models.ForeignKey(Author, blank=True, null=True)
author_email = models.EmailField('Author email', max_length=75, blank=True)
imported = models.BooleanField(default=False)
published = models.DateField('Published', blank=True, null=True)
price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
categories = models.ManyToManyField(Category, blank=True)
def __str__(self):
return self.name
Resource配置
關(guān)于Resource配置的更多可以參考官方文檔,不想啃文檔可以看我上一篇文章:Django數(shù)據(jù)導(dǎo)入導(dǎo)出神器django-import-export使用
from import_export import fields, resources
from import_export.widgets import ForeignKeyWidget
class BookResource(resources.ModelResource):
author = fields.Field(
column_name='author',
attribute='author',
widget=ForeignKeyWidget(Author, 'name'))
class Meta:
fields = ('author',)
搞定,這樣在導(dǎo)入的時候會自動關(guān)聯(lián)外鍵author。
參考資料
官方文檔:https://django-import-export.readthedocs.io/en/latest/api_widgets.html#import_export.widgets.ForeignKeyWidget Django-10-導(dǎo)入導(dǎo)出功能優(yōu)化:https://www.jianshu.com/p/f82a465a41d8 django-import-export關(guān)聯(lián)外鍵在后臺管理中導(dǎo)入導(dǎo)出的辦法:https://blog.csdn.net/weixin_38496380/article/details/104717236
歡迎交流
程序設(shè)計實驗室專注于互聯(lián)網(wǎng)熱門新技術(shù)探索與團(tuán)隊敏捷開發(fā)實踐,在公眾號「程序設(shè)計實驗室」后臺回復(fù) linux、flutter、c#、netcore、android、kotlin、java、python 等可獲取相關(guān)技術(shù)文章和資料,同時有任何問題都可以在公眾號后臺留言~
博客園:https://www.cnblogs.com/deali/ 打代碼直播間:https://live.bilibili.com/11883038 知乎:https://www.zhihu.com/people/dealiaxy

