I'm trying to understand how Django management commands work.
When there's no argument, or self on it's own. my command works fine. When I add arguments to the second function 'def add_arguments' it seems one arg works but the other isn't registering.
My command is as follows:
from backend.tasks import MBCommand
import sys
class Command(MBCommand):
help = 'Refreshes MB data'
def add_arguments(self , parser):
parser.add_argument('event_id' , nargs='+' , type=int,
help='evid')
parser.add_argument('market_id', nargs='+', type=int,
help='marid')
def handle(self, *args, **kwargs):
self.mb_get_events()
event_ids = kwargs['event_id']
market_ids = kwargs['market_id']
for event_id in event_ids:
for market_id in market_ids:
self.mb_get_runners(event_id,market_id)
sys.exit()
My two functions are,
from django.core.management.base import BaseCommand, CommandError
class MBCommand(BaseCommand):
def mb_get_events(self):
do something
def mb_get_runners(self, event_id, market_id):
do something
What am I missing here?
how I run the command (update_mb is the file name of command)
python manage.py update_mb event_id market_id
the error.
usage: manage.py update_mb [-h] [--version] [-v {0,1,2,3}]
[--settings SETTINGS] [--pythonpath
PYTHONPATH]
[--traceback] [--no-color]
event_id [event_id ...] market_id [market_id
...]
manage.py update_mb: error: argument event_id: invalid int
value:
'event_id'
(butterbotenv) macs-MBP:butterbot mac$
As I already said in the comments to the question:
The command expects one (or multiple) arguments of type int; but as the error says, it cannot cast the received argument into a int.
Try passing numbers; instead of
python manage.py update_mb event_id market_id
try using this (or something similar)
python manage.py update_mb 2 3 4
But I notice an issue with your code: you use parser.add_argument(... nargs='+', ...) for both of your arguments. Consider the example I gave previously:
python manage.py update_mb 2 3 4
How is the command supossed to know which are event_id and which are market_id? How does it work for you?
One improvement could be to use optional arguments; read more about Djangos custom management commands and the underlying Python argparse module.
It could look like this:
def add_arguments(self , parser):
parser.add_argument('--event', action='append', type=int)
parser.add_argument('--market', action='append', type=int)
To be used like this:
>>> python manage.py update_mb --event 2 --event 3 --market 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With