Use the Django ORM in a standalone script (again)

前端 未结 3 1463
情歌与酒
情歌与酒 2021-02-01 11:07

I\'m trying to use the Django ORM in some standalone screen scraping scripts. I know this question has been asked before, but I\'m unable to figure out a good solution for my pa

相关标签:
3条回答
  • 2021-02-01 11:14

    I know this question is six years old but this alternative might appeal to someone searching this topic. Assuming Django's manage.py is in project/, and assuming main() is the script's entrypoint, then let Django take the strain:

    ./manage.py shell -c 'from scrape.test import main; main()'
    
    0 讨论(0)
  • 2021-02-01 11:31

    Found an easy way to reuse existing django app's settings for console script:

    from django.core.management import setup_environ
    
    import settings
    setup_environ(settings)
    
    from myapp.models import Object
    
    for o in Object.objects.all():
        print o
    
    0 讨论(0)
  • 2021-02-01 11:32

    Are you sure it shouldn't be:

    sys.path.append(os.path.join(os.path.abspath('..'), 'web'))
    

    Also, make sure there's an __init__.py file (empty is fine) in project/web/django_project.

    P.S. I'd recommend feeding os.path.join's output to os.path.abspath instead of the other way.

    0 讨论(0)
提交回复
热议问题