简体   繁体   English

如何从脚本自动创建 django model 实例?

[英]How can I automate the creation of django model instances from a script?

I'm fairly new to Django and recently created a website to group and display COVID-19 data in my home country.我对 Django 还很陌生,最近创建了一个网站来分组和显示我本国的 COVID-19 数据。

I am recording daily new cases, deaths, and recoveries by city using a CaseDeclaration model:我使用 CaseDeclaration model 按城市记录每日新增病例、死亡人数和康复人数:

class CaseDeclaration(models.Model):
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    date = models.DateField(default=lambda: CaseDeclaration.latest_date())
    new_cases = models.IntegerField(default=0)
    new_deaths = models.IntegerField(default=0)
    new_recoveries = models.IntegerField(default=0)
    source = models.URLField(max_length=200, blank=True)

It is working properly but I am now writing a script that will automate the process of creating CaseDeclaration objects off of publications made by a local news outlet on Facebook.它工作正常,但我现在正在编写一个脚本,该脚本将自动从 Facebook 上的本地新闻媒体发布的出版物中创建 CaseDeclaration 对象的过程。 The script is in a text_extractor.py file next to models.py and views.py.该脚本位于 models.py 和 views.py 旁边的text_extractor.py文件中。 At this point it takes a txt file and extracts the data into a dictionary like so (keys are the city names):此时它需要一个 txt 文件并将数据提取到字典中,如下所示(键是城市名称):

>>> print(extract_data())
{'non répertorié': {'new_deaths': 6, 'new_recoveries': 344}, 'Antananarivo': {'new_cases': 388}, 'Ambatondrazaka': {'new_cases': 13}, 'Toliara': {'new_cases': 9}, 'Fianarantsoa': {'new_cases': 7}, 'Mahajanga': {'new_cases': 6}, 'Ambositra': {'new_cases': 3}, 'Miarinarivo': {'new_cases': 2}, 'Toamasina': {'new_cases': 2}, 'Sambava': {'new_cases': 1}}

And the date extract_date() returns the format 8-11-2020 as a str.日期extract_date()以 str 形式返回格式 8-11-2020。

I now need a way to take that data and create model instances for each city, all without me having to use the python shell or admin panel.我现在需要一种方法来获取这些数据并为每个城市创建 model 实例,而无需我使用 python shell 或管理面板。 And finally program the script to execute daily .最后编写脚本以每天执行

What I have tried so far:到目前为止我已经尝试过:

  1. import models into my text_extractor.py file and use Model().save() from there, but my file could not import models, and I could not figure out how to run the script from the server from there.将模型导入我的 text_extractor.py 文件并从那里使用 Model().save() ,但是我的文件无法导入模型,我无法弄清楚如何从那里从服务器运行脚本。
  2. create a Model Manager for CaseDeclaration and give it a create_from_dict() function为 CaseDeclaration 创建一个 Model 管理器并给它一个 create_from_dict() function
  3. create a function that will create the model instances and run it every time the home page is loaded * and the latest CaseDeclaration object is not from today.创建一个 function 将创建 model 实例并在每次加载主页时运行它*并且最新的 CaseDeclaration object 不是从今天开始的。 Also, here my custom.py file isn't recognized as a module and can't be imported.另外,这里我的 custom.py 文件未被识别为模块,无法导入。

Whichever way would eventually work I am not capable to figure it out by myself and online resources have been really limited, so I am hoping you can help out.无论哪种方式最终会奏效,我自己都无法弄清楚,并且在线资源非常有限,所以我希望您能提供帮助。 Thank you so much in advance!非常感谢您!

EDIT: Current code text_extractor.py编辑:当前代码text_extractor.py

def extract_data():
    return find_data(region_to_cities(join_words(cleanup_covid19(extracted_data))))

def extract_date():
    temp = find_date(region_to_cities(join_words(cleanup_covid19(extracted_data))))
    date = '-'.join(str(e) for e in temp)
    return date

views.py视图.py

def extractCaseDeclaration():
    from .text_extractor import extract_data, extract_date
    data = extract_data()
    date = datetime.datetime.strptime(extract_date(), '%m-%d-%Y')

    for key, values in data.items():
        city = ''
        if "-" in key:
            city = string.capwords(key, '-')
        else:
            city = string.capwords(key)
        print(city)
        city = City.objects.get(name = city)

extractCaseDeclaration()

You can run the python script in the manage.py shell just start the shell:您可以在 manage.py 中运行 python 脚本 shell 只需启动 shell:

python manage.py shell

and run the code snippet below并运行下面的代码片段

>>>exec(open('/python_automate_script.py').read())

This will run the python script.这将运行 python 脚本。

There are other ways, you can find more details in thiswebsite还有其他方法,您可以在本网站找到更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM