Handling Foreign Keys in the Django-Import-Export Plugin
Preface Django-Import-Export is a very useful and convenient Django data import/export plugin that integrates perfectly with the Django Admin backend. With just a small amount of code configuration, you can easily implement import and export in various formats as needed. For more on how to use this plugin, you can check my previous article: put the article link here Previously when using it, I always created a dedicated raw data table to store the imported data, then did some data processing on the raw data table and stored the data in other tables before it could actually be used. (Not a very good
目录6 个章节
Preface
Django-Import-Export is a very useful and convenient Django data import/export plugin that integrates perfectly with the Django Admin backend. With just a small amount of code configuration, you can easily implement import and export in various formats as needed. For more on how to use this plugin, you can check my previous article: put the article link here
Previously when using it, I always created a dedicated raw data table to store the imported data, then did some data processing on the raw data table and stored the data in other tables before it could actually be used. (Doesn't seem like a great approach)
Now what I need is to import data based on the existing table structure, and the table I need to import data into also has several foreign keys, which involves handling foreign keys.
So I searched online for a long time (Google-oriented programming). Domestic materials mainly consist of the two articles in the references. After looking at them, they solved it with somewhat fancy hacky tricks, which felt so-so. That kind of hack couldn't satisfy me, so I gave up on Google and went straight to grinding through the official docs (I really regret why I didn't just grind through the official docs from the start...)
Solution
The real solution still has to come from the official documentation.
Model Configuration
First let's see how the models are defined. I'll put the official examples here; my own project's model has too many fields, so looking at the official ones is clearer.
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 Configuration
For more on Resource configuration, you can refer to the official documentation. If you don't want to grind through the docs, you can check my previous article: article link
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',)
Done. This way, during import it will automatically associate the foreign key author.
References
- Official documentation: https://django-import-export.readthedocs.io/en/latest/api_widgets.html#import_export.widgets.ForeignKeyWidget
- Django-10 Import/Export Feature Optimization: https://www.jianshu.com/p/f82a465a41d8
- A method for django-import-export related foreign keys import/export in admin: https://blog.csdn.net/weixin_38496380/article/details/104717236
Welcome to Chat
Programming Lab focuses on exploring popular new internet technologies and team agile development practices. Reply with linux, flutter, c#, netcore, android, kotlin, java, python, etc. in the backend of the WeChat official account "Programming Lab" to get related technical articles and materials. If you have any questions, you can also leave a message on the official account~
- Cnblogs: https://www.cnblogs.com/deali/
- Coding livestream: https://live.bilibili.com/11883038
- Zhihu: https://www.zhihu.com/people/dealiaxy
_EOF_
Handling Foreign Keys in the Django-Import-Export Plugin
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
配置Django-TinyMCE组件支持上传图片功能
Django自带的Admin后台,好用,TinyMCE作为富文本编辑器,也蛮好用的,这两者结合起来在做博客的时候很方便(当然博客可能更适合用Markdown来写),但是Django-TinyMCE这个组件默认没有图片上传功能的,需要我们自己实现,本文将一步步带大家实现这个图片上传功能。 读者也可以举一反三实现其他需要和Django结合的功能。 编写上传图片逻辑 在任一views.py里添加代码:
2021-12-18 · Django · 约 1 分钟
在 django-ninja 中实现类似腾讯阿里云的应用鉴权机制
Django-Ninja API鉴权机制?不就是又一套基于AppClient的认证系统,支持查询参数、请求头、Bearer Token认证,外加IP白名单和scopes权限控制?代码写得够复杂,够绕?
2025-07-10 · Django · 约 1 分钟
Django-Filter介绍与刁钻需求的实现方法
Django-Filter是一个非常好用的第三方库,很好的利用了Django ORM的特性,可以使用很少的代码就扩展原有的接口,实现多种筛选功能~ 场景 Model定义的部分代码,可以看到需求模型包括了 关键词 keyword、区域 region、需求状态 require_status,这三个字段 class Require(models.Model): 需求 keyword =
2021-12-18 · Django · 约 1 分钟
轻松搞定Django分页功能
view代码 from django.core.paginator import Paginator def announcement(request): ctx = { 'global': GlobalCtx, 'announcements': models.Announcement.objects.all(), } paginator
2022-05-27 · Django · 约 1 分钟
讨论
共 0 条加载评论中…