Python 如何通过Bash脚本将模型查询导入Django Shell?
我正在编写一个startup.sh脚本,在创建docker容器时运行Python 如何通过Bash脚本将模型查询导入Django Shell?,python,django,bash,shell,Python,Django,Bash,Shell,我正在编写一个startup.sh脚本,在创建docker容器时运行 #!/bin/bash python manage.py runserver python manage.py makemigrations accounts python manage.py migrate python manage.py check_permissions python manage.py cities --import=country --force *python manage.py she
#!/bin/bash
python manage.py runserver
python manage.py makemigrations accounts
python manage.py migrate
python manage.py check_permissions
python manage.py cities --import=country --force
*python manage.py shell | from cities.models import * Country.objects.all().exclude(name='United States").delete()*
python manage.py cities --import=cities
python manage.py cities --import=postal_code
我猜这行代码是不正确的,在bash脚本中这样做的正确方法是什么?在shell脚本文件中包含django代码不是一个好主意。最好制作一个python文件并将这些代码放入其中,然后执行以下操作:
python manage.py shell < script.py
python manage.py shell
或者最好写一封信。通过这种方式,您可以在同一个项目/回购中跟踪代码,人们在看到这一点时不会感到困惑。使用heredoc:
python manage.py shell <<'EOF'
from cities.models import *
Country.objects.all().exclude(name='United States').delete()
EOF
python manage.py shell也愿意接受任何关于如何更好地实现这一点的建议,比如尝试更好地了解bash中管道的工作方式--foo | bar
将foo
的stdout连接到bar
的stdin。因此,您建议的命令使用其第二个参数cities.models
,&c将python manage.py shell的输出发送到名为from
、名为的命令的输入。您可以用另一种方式执行此操作:printf“%s\n”from cities.models import*''Country.objects.all().exclude(name=“United”).delete()“| python manage.py shell
——这样,您就可以将生成脚本的printf
命令的输出发送到manage.py shell
命令。我将尝试此方法。对于管理命令建议,请竖起大拇指。实际上,我认为我更喜欢management命令方法或herdeoc方法,而不是python manage.py shell