adm*_*tad 4 python django django-models
我正试图从常规Python脚本中访问我的Django数据库.到目前为止,我所做的是:
import os
import django
from django.db import models
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "m_site.settings")
django.setup()
from django.apps import apps
ap=apps.get_model('py','Post')
q=ap.objects.all()
for a in q:
print(a.title)
Run Code Online (Sandbox Code Playgroud)
在Django中有一个应用程序叫做py我有很多帖子(models.py包含class Post(models.Model)).
我希望有可能从常规Python脚本访问和更新此数据库.到目前为止上面的脚本工作正常,我可以插入,更新或查询,但它看起来像是一个单独的数据库,而不是Django的py应用程序中的数据库.我做错了什么或遗失了什么?任何帮助将非常感激.
考虑将脚本编写为自定义管理命令.这将让你通过它运行它manage.py,Django所有正确连线,例如
python manage.py print_post_titles
Run Code Online (Sandbox Code Playgroud)
这样的事情应该是一个好的开始:
from django.core.management.base import BaseCommand
from py.models import Post
class Command(BaseCommand):
help = 'Prints the titles of all Posts'
def handle(self, *args, **options):
for post in Post.objects.all():
print(a.title)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2309 次 |
| 最近记录: |