Django:自动删除记录
Django: automatically delete records
我正在尝试实时或自动删除记录类似于this
据我了解(我是新手)你需要写一个管理命令,但我很难理解这个概念,它怎么能实时呢?有人能指出我正确的方向吗?我很迷茫。提前谢谢你。
你想知道的关于自定义 Django 命令的一切都可以在文档中找到:https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/
基本上,您需要创建一个 management/commands
目录,因此您的文件夹结构如下所示:
app/
... (some stuff you're having in your app directory)
management/
__init__.py
commands/
__init__.py
delete_all.py
现在,在 delete_all.py
中,您想声明一个新命令 class 扩展 BaseCommand
并负责您的所有逻辑。最简单的实现如下所示:
# delete_all.py
from django.core.management.base import BaseCommand
from app.models import MyModel
class Command(BaseCommand):
def handle(self, *args, **options):
print('Deleting all MyModel records!')
MyModel.objects.all().delete()
print('Successfully deleted all MyModel records!')
现在您可以使用 manage.py
访问您的命令:
python manage.py delete_all
我正在尝试实时或自动删除记录类似于this
据我了解(我是新手)你需要写一个管理命令,但我很难理解这个概念,它怎么能实时呢?有人能指出我正确的方向吗?我很迷茫。提前谢谢你。
你想知道的关于自定义 Django 命令的一切都可以在文档中找到:https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/
基本上,您需要创建一个 management/commands
目录,因此您的文件夹结构如下所示:
app/
... (some stuff you're having in your app directory)
management/
__init__.py
commands/
__init__.py
delete_all.py
现在,在 delete_all.py
中,您想声明一个新命令 class 扩展 BaseCommand
并负责您的所有逻辑。最简单的实现如下所示:
# delete_all.py
from django.core.management.base import BaseCommand
from app.models import MyModel
class Command(BaseCommand):
def handle(self, *args, **options):
print('Deleting all MyModel records!')
MyModel.objects.all().delete()
print('Successfully deleted all MyModel records!')
现在您可以使用 manage.py
访问您的命令:
python manage.py delete_all