2017-08-21 11 views
0

csvファイルに新しい行があるかどうかをチェックしたいpythonファイルを実行します。新しい行がある場合は、データベースに追加する必要があります。次のようにDjangoでモデルをインポートする方法

プロジェクトツリーは、次のとおりです。

enter image description here

このように、私が実行したいファイルがrelationsフォルダ内check_relations.pyです。次のように

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) 

モデルTraxioRelationsmasterフォルダにmodels.pyの内側にあります。私は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ファイル内でモデルをインポートするにはどうすればよいですか?

+0

'はImportError:いいえモジュールという名前のモデル' – Boky

+0

前のコメントを無視します。外部から(django内からではなく)ファイルを実行しているので、 'traxio'があなたのシステムパスに存在する必要があります。代わりに' traxio.master.models import ... 'を実行する必要があります。 –

答えて

2

私はそれはあなたのマスター・カタログに例えばcommands

を作成し、最も使用可能な方法だと思う: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) 

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

を!は、ファイルAUTOI_Relaties.csvへのパスを変更したり、新しいディレクトリ

にそれを置くことを忘れないでくださいと、あなたは、シェルで実行することができます。同じエラー@AshishNitinPatil

./manage.py check_relations 
関連する問題