首页 > 解决方案 > 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.

标签: pythonmysqldjangodatabasedata-synchronization

解决方案


没有预先构建的命令可能会满足您的确切需求,但是 python 具有良好的csv读取实用程序,您可以编写自定义Django 命令来读取您的 csv 文件并添加、删除或更新您的用户模型。

除非你有特殊要求——例如,巨大的数据集或其他限制——我建议与 Django 的模型层进行交互以进行更改,而不是直接与数据库交互。这样,如果您对未在数据库级别表示的用户模型进行任何特殊验证(选择、整数范围等),您将避免引入数据不一致。

最后的想法 - 在你的命令中,考虑使用 Django 的 ORM 提供的以下优秀方法:Manager.get_or_createManager.update_or_create。它们对于避免重复数据和优雅地告诉 ORM 就地创建或修改等很有用。

祝你好运!


推荐阅读