1

I'm writing a custom django management command.

class Command(BaseCommand):

    option_list = BaseCommand.option_list + (
        make_option(
            "-i",
            "--user_id",
            dest="user_id",
        ),
        make_option(
            "-f",
            "--fields",
            dest="fields"
        ),
    )

I need fields to consist of multiple elements. I know about nargs but I need to specify an exact number. My fields can vary from 1 to 5 elements. Is there a proper way to work with such args lists?

1 Answer 1

2

It's not possible to do this automatically. But you can work with a different action type:

option_list = BaseCommand.option_list + (
    make_option(
        "-i",
        "--user_id",
        dest="user_id",
    ),
    make_option(
        "-f",
        "--fields",
        dest="fields",
        action="append",
    ),
)

Now supply multiple field names at the command line like so:

./my_program -u my_user -f field1 -f field2 -f field3

options['fields'] will then contain a list of field names or None. You can check for this (and the fact that the list is longer than five elements) and print an error message.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.