ncica
ncica

Reputation: 7206

Custom Django management command

The idea is to delete an object by accepting command line options:

Expected behavior, new custom command call using:

python manage.py delete_obj --delete id 1234

or

python manage.py delete_obj --delete from 2019/10/01 to 2019/12/12

Code for the first part:

from django.core.management.base import BaseCommand
from ...models import SomeObject

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('id', type=int)

        parser.add_argument(
            '--delete',
            default = False,
            help='Delete product',
        )

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

        if options['delete']:
            if options['id']:

                SomeObject.delete()

I add a custom option in the add_arguments() method for id. How can I define that object to be deleted by ID or by DATE RANGE?

Upvotes: 1

Views: 1778

Answers (1)

JPG
JPG

Reputation: 88659

Something like this:

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('--id', type=int)
        parser.add_argument('--date_from')
        parser.add_argument('--date_to')

    def handle(self, *args, **options):
        if options['id']:
            try:
                instance = SampleModel.objects.get(id=options['id'])
                instance.delete()
                self.stdout.write(self.style.SUCCESS('Object Deleted'))
            except SampleModel.DoesNotExist:
                self.stdout.write(self.style.ERROR('Object not found'))
        elif options['date_from'] and options['date_to']:
            date_range = [options['date_from'], options['date_to']]
            SampleModel.objects.filter(datetime_field__range=date_range).delete()
            self.stdout.write(self.style.SUCCESS('Objects Deleted'))
        else:
            self.stdout.write(self.style.ERROR('options are not given'))

Usage:

python manage.py command_name --id 123
python manage.py command_name --date_from 2012-12-12 --date_to 2013-12-12

The basic idea is, you can pass any number of arguments to your Django command, and Django is able to typecast the input value to any native Python data type.

Upvotes: 5

Related Questions