首页 > 解决方案 > 用于访问模型对象的 Django 脚本

问题描述

我的 django 项目叫 mybooks,应用是列表。我正在编写一个名为 searchBooks.py 的 python 脚本,它需要列表应用程序中的一些模型。searchBooks.py 脚本位于列表文件夹中(与 models.py 相同)但是,我无法访问模型。

我做了其他一些用户在这里提出的建议,包括

import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mybooks.settings") from listings.models import books

但是,我得到 ModuleNotFoundError: No module named 'listings'

我应该更改 settings.py 中的任何内容吗?或者可能是 searchBooks.py 的目录?

标签: pythondjangosettings

解决方案


您需要编写一个在 Django 上下文中运行的脚本,通过manage.py. 这很容易。

在您的应用程序中,首先创建app/management/commands/__init__.py(空文件,您可能需要创建文件夹)。然后,首先将此模板复制到app/management/commands/noop.py

# invoke with ./manage.py noop [--total] 1 2 3 ...
# script in  app/management/noop.py with __init__.py

from django.core.management.base import BaseCommand

class Command( BaseCommand):

    def add_arguments( self, parser):    # parser is Python argparse parser

        parser.add_argument( 'number_list', nargs='+', type=int,
            help='any number of integers to add up',
        )

        parser.add_argument( '--total', action='store_true', default=False,
            help='Print the total as well as the args'
        )

        parser.add_argument( '--file', type=self.infile)

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

        # print( f'Args: {args}' )    # what are args?

        if options['verbosity'] >= 2:  # inherit default options, including verbosity and help.
                                       # use --help to explore the others
            print( f'Options: {options}' )

        if options['total']:
            total = sum( options['number_list'])
            print( f'Total: {total}' )

        if options['file']:
            print('First line is:')
            print( options['file'].readline() )


    def infile( self, arg):
        return open( arg, 'r')

如果您不熟悉 argparse,请查阅其文档(它是标准 Python,而不是 Django):https ://docs.python.org/3/library/argparse.html

一旦你确定它有效,你可以得到六个

./manage.py noop --total 1 2 3

将其作为起点复制到同一文件夹中的某个其他名称,然后对其进行修改以执行您希望从命令行执行的任何操作。您将首先添加

from listings.models import Whatever, ...

然后根据您定义的任何选项的指示,修改句柄方法以对它们做任何您想做的事情。

Django 文档:https ://docs.djangoproject.com/en/2.1/howto/custom-management-commands/


推荐阅读