Django custom command object ID not found
Clash Royale CLAN TAG#URR8PPP
Django custom command object ID not found
SOLVED:
The try - catch was finding something at a later step in the process
I moved these steps outside of the try - catch and resolved those issues
I'm trying to build a custom Django command which can be run against individual model objects
When I check in shell I see the object fine
>>> Obj.objects.get(id=1)
<Obj: the object I'm looking for>
My custom command however looks like the below:
# app/management/update.py
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--id')
def handle(self, *args, **options):
if options['id']:
try:
obj = Obj.objects.get(id=options['id'])
# do things
except:
raise CommandError('no object with ID: "%s"' % options['id'])
else:
# do other things
Running this I get the error message
>>> python manage.py update --id 1
CommandError: no object with ID: "1"
Any help appreciated.
Thanks
ID=1
ID=2
Log the exact Exception. With your bare
except
(never do that!), you obscure what actually happens and just assume what might be the reason.– schwobaseggl
Aug 10 at 13:50
except
1 Answer
1
Id should be an integer, not a string.
parser.add_argument('--id', type=int)
By default, ArgumentParser
objects read command-line arguments in as
simple strings. However, quite often the command-line string should
instead be interpreted as another type, like a float
or int
. The type
keyword argument of add_argument()
allows any necessary type-checking
and type conversions to be performed.
ArgumentParser
float
int
type
add_argument()
https://docs.python.org/3/library/argparse.html#type
It won't matter in the query whether you use
1
or '1'
. Django querysets are robust that way.– schwobaseggl
Aug 10 at 13:48
1
'1'
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
In example your have
ID=1
but in commandID=2
?– Rakesh
Aug 10 at 13:18