用于访问模型对象的Django脚本

问题描述 投票:0回答:1

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

我做了一些其他用户建议的here,包括

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

但是,我得到ModuleNotFoundError:没有名为'listing'的模块

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

python django settings
1个回答
1
投票

您需要编写一个在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,请参考它的documntation(它的标准Python,而不是Django):https://docs.python.org/3/library/argparse.html

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

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

将其作为起点复制到同一文件夹中的其他名称,并对其进行修改以执行您希望从命令行执行的任何操作。你将从添加开始

from listings.models import Whatever, ...

然后根据您定义的任何选项的指示,修改handle方法以对其执行任何操作。

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

© www.soinside.com 2019 - 2024. All rights reserved.