如何填充Django sqlite3数据库

1 投票
1 回答
1734 浏览
提问于 2025-04-15 16:53

我的计划是从一些网站上批量收集律师的个人资料数据,然后把每一批数据转换成一个.csv文件,再转换成json格式,最后把这些数据导入到Django数据库里。

请告诉我最好的方法来完成这个任务。

1 个回答

7

直接加载数据库就行。一次性从网站上收集数据,然后直接加载到SQLite3数据库里。只需要写一些简单的批处理程序,使用Django的ORM工具。收集完网站的数据后,立刻加载到SQLite3里。不要创建CSV文件,也不要生成JSON格式的数据。不要做中间结果,也不要做任何额外的工作。


编辑。

from myapp.models import MyModel
import urllib2

with open("sourceListOfURLs.txt", "r" ) as source:
    for aLine in source:
        for this, the, the_other in someGenerator( aLine ):
            object= MyModel.objects.create( field1=this, field2=that, field3=the_other )
            object.save()

def someGenerator( url ):
    # open the URL with urllib2
    # parse the data with BeautifulSoup
    yield this, that, the_other 

撰写回答