python - Synchronizing data from external source to db used in django project?
问题描述
I need to synchronize data from a csv-file every night to update the data in my django project (I'm using mysql as backend). The data contains user information - sometimes users are to be removed, sometimes new user has to be added and sometimes some of the information about a specific user has changed and needs to be updated. I need to keep this in sync. Are there any built in functions to do this (i.e. manage.py/django-admin)? Do I write a python script and work with my django models to manipulate the data? Is it ok/safe to work directly with the tables in the database, bypassing the models? What is best practice?
I'm using Python 3.7 and Django 2.1 if this helps.
解决方案
没有预先构建的命令可能会满足您的确切需求,但是 python 具有良好的csv读取实用程序,您可以编写自定义Django 命令来读取您的 csv 文件并添加、删除或更新您的用户模型。
除非你有特殊要求——例如,巨大的数据集或其他限制——我建议与 Django 的模型层进行交互以进行更改,而不是直接与数据库交互。这样,如果您对未在数据库级别表示的用户模型进行任何特殊验证(选择、整数范围等),您将避免引入数据不一致。
最后的想法 - 在你的命令中,考虑使用 Django 的 ORM 提供的以下优秀方法:Manager.get_or_create和Manager.update_or_create。它们对于避免重复数据和优雅地告诉 ORM 就地创建或修改等很有用。
祝你好运!
推荐阅读
- apache-flink - 当 Flink+Redisson 运行异常,反复重试时,Redis 连接数会不断增长,最终达到上限
- google-api - Google reCaptcha 通过 API 创建凭据
- postgresql - 使用 timescaledb 和 postgresql 12 进行复制时,使用 pg_basebackup 时容器关闭
- pandas - 如何在数据框中的两列中找到部分匹配项
- reactjs - Docusaurus 2 如何在导航栏中添加自定义反应组件
- matlab - pdist 输入数据设置错误 - Matlab
- javascript - 修改表
- r - 是否有一个函数可以获取相同类型的行之间的差异?
- javascript - 如何确保在循环内打开正确的引导模式
- android - 在 Android 中点击 One Signal 推送通知时如何导航到特定页面?