如何在Django中导入模型

时间:2017-08-21 08:37:42

标签: python django

我想执行一个python文件,我想检查csv文件中是否有新行。如果有新行,我想将它们添加到数据库中。

项目树如下:

enter image description here

因此,我要执行的文件是check_relations.py文件夹中的relations

check_relations.py如下:

from master.models import TraxioRelations

with open('AUTOI_Relaties.csv', 'rb') as tr:
    traxio_relations = tr.readlines()

for line in traxio_relations:
    number = line.split(';')[0]
    number_exists = TraxioRelations.objects.filter(number=number)
    print(number_exists)

模型TraxioRelations位于models.py文件夹中的master内。

当我运行python check_relations.py时出现错误

Traceback (most recent call last):
  File "check_relations.py", line 3, in <module>
    from master.models import TraxioRelations
ImportError: No module named master.models

我做错了什么?如何在check_relations.py文件中导入模型?

2 个答案:

答案 0 :(得分:3)

我认为最有用的方式是创建commands

例如在主目录中:

master /
    management /
        __init__.py
        commands /
            __init__.py
            check_relations.py
check_relations.py

中的

from django.core.management.base import BaseCommand
from master.models import TraxioRelations

class Command(BaseCommand):
    help = 'check_relations by file data'

    def handle(self, *args, **options):

        with open('AUTOI_Relaties.csv', 'rb') as tr:
            traxio_relations = tr.readlines()

        for line in traxio_relations:
            number = line.split(';')[0]
            number_exists = TraxioRelations.objects.filter(number=number)
            print(number_exists)

请勿忘记更改文件AUTOI_Relaties.csv的路径或将其放入新目录

然后你可以在shell中运行:

./manage.py check_relations

答案 1 :(得分:1)

使用Django时,您不应该自己运行单个模块。参见例如https://docs.djangoproject.com/en/1.11/intro/tutorial01/#the-development-server