gpt4 book ai didi

python - 用于通过解析器中的参数从特定模型中删除数据的 BaseCommand

转载 作者:太空宇宙 更新时间:2023-11-03 15:34:27 25 4
gpt4 key购买 nike

我需要一个 BaseCommand 来删除参数中指定模型的条目。

运行这个:./manage.py delete_data_model app.shop

# delete_data_model.py

from django.core.management.base import BaseCommand, CommandError
from django.db.transaction import atomic


class Command(BaseCommand):
help = "Deleted data from model"

def add_arguments(self, parser):
parser.add_argument('model', required=True, type=str)

def handle(self, *args, **options):
self.stdout.write("Begin")
with atomic(using='default'):
try:
path = options['model']
app, model = path.split('.')[:2]
from (app) import (model) as Model # ??? how do this
Model.objects.all().delete()
except Exception as e:
raise CommandError("Error {}".format(e))
self.stdout.write("Complete")

我希望空表 Shop。

最佳答案

试试这个

from django.core.management.base import BaseCommand, CommandError
from django.db.transaction import atomic
<b>from django.apps import apps</b>


class Command(BaseCommand):
help = "Deleted data from model"

def add_arguments(self, parser):
parser.add_argument('model', required=True, type=str)

def handle(self, *args, **options):
self.stdout.write("Begin")
with atomic(using='default'):
try:
path = options['model']
app, model = path.split('.')[:2]
<b>Model = apps.get_model(app_label=app, model_name=model)</b>
Model.objects.all().delete()
except Exception as e:
raise CommandError("Error {}".format(e))
self.stdout.write("Complete")

引用:
1. Django: Get model from string?
2. apps.get_model(app_label, model_name, require_ready=True) -- Django Doc

关于python - 用于通过解析器中的参数从特定模型中删除数据的 BaseCommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55723126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com