Django: Getting Started Transcripts
Chapter: Custom Django Commands
Lecture: Writing management commands with arguments

Login or purchase this course to watch this video and the rest of the course contents.
0:00 The next command will give info about a book. I'll call it book, like before I need to create the file in the commands subdirectory.
0:32 The top of the file looks very similar to authors. I'm importing the book the base command and creating the command and specifying the help.
0:39 I want the book command to take arguments so I'm going to override the base commands add arguments method.
0:45 The add arguments method takes a parameter which is an arg parse parser which I can then use to add command line arguments.
1:01 Arg parse is a pretty deep library. I won't get into it here but anything you can do with it, you can do with your management command.
1:09 In this one I've added two arguments, the first one is --all the store true action indicates that a bullion should be created in the options dictionary
1:19 called all and set to true if the user gave this flag. The help parameter is the argument specific help message.
1:29 The second call to add argument specifies that there can be several arguments. It's called book IEDs and the narg equals star means to
1:39 expect multiple arguments, all of which will be stored in a list.
1:44 By setting the type to int arg parse will automatically take the command line contents which is always text and convert it to integers.
1:52 If you pass in something that isn't an integer, it will complain. That means you don't have to check any of that stuff yourself which is nice.
2:00 As with --all, the help parameter here is an argument for specific help for the book IDs argument. With all the arguments added,
2:11 now I have to do is write the logic for the command. Like before I'm going to override the handle method as the entry point.
2:28 The options dictionary will be populated with any arguments that were defined in the add argument method.
2:34 The first thing I do here is check for the --all flag and if it's there, I'm populating a books variable with all of the books in the system.
2:53 If the --all flag isn't there, then I look at the book IDs list and create a filter of books based on that list.
3:01 If everything is normal at this point in the code, you'll have a query set result containing some book objects.
3:11 In the case where the user didn't give any of the expected arguments, you can raise an exception.
3:17 The command error exception is handled by the base command and will properly output an error message. This won't trigger a trace back.
3:48 And finally, just like the author's command, I iterate over some objects. Books this time sticking the info in a list,
3:54 then write it all to standard out. Let's go look at book command.


Talk Python's Mastodon Michael Kennedy's Mastodon