Parsers

Typer supports custom parsers for options and arguments. If you would like to type a parameter with a type that isn’t supported by Typer you can implement your own parser, or click.ParamType in click parlance.

This package contains a collection of parsers that turn strings into useful Django types. Pass these parsers to the parser argument of typer.Option and typer.Argument. Parsers are provided for:

  • models, querysets or field values: Turn a string into a model object instance

    using ModelObjectParser.

  • Django apps: Turn a string into an AppConfig instance using

    app_config().

Warning

If you implement a custom parser, please take care to ensure that it:
  • Handles the case where the value is already the expected type.

  • Returns None if the value is None (already implemented if subclassing ParamType).

  • Raises a CommandError if the value is invalid.

  • Handles the case where the param and context are None.

django_typer.parsers.apps.app_config(label)[source]

A parser for app label. If the label is already an AppConfig instance, the instance is returned. The label will be tried first, if that fails the label will be treated as the app name.

import typing as t
import typer
from django_typer.management import TyperCommand
from django_typer.parsers import app_config

class Command(TyperCommand):

    def handle(
        self,
        django_apps: t.Annotated[
            t.List[AppConfig],
            typer.Argument(
                parser=app_config,
                help=_("One or more application labels.")
            )
        ]
    ):
        ...
Parameters:

label (str | AppConfig) – The label to map to an AppConfig instance.

Raises:

CommandError – If no matching app can be found.

class django_typer.parsers.model.ModelObjectParser(model_cls, lookup_field=None, case_insensitive=False, on_error=None, return_type=ReturnType.MODEL_INSTANCE)[source]

A parser that will turn strings into model object instances based on the configured lookup field and model class.

from django_typer.parsers.model import ModelObjectParser

class Command(TyperCommand):
    def handle(
        self,
        django_apps: Annotated[
            t.List[MyModel],
            typer.Argument(
                parser=ModelObjectParser(MyModel, lookup_field="name"),
                help=_("One or more application labels."),
            ),
        ],
    ):

Note

Typer does not respect the shell_complete functions on ParamTypes passed as parsers. To add shell_completion see ModelObjectCompleter or the model_parser_completer() convenience function.

Parameters:
  • model_cls (Type[Model]) – The model class to use for lookup.

  • lookup_field (str) – The field to use for lookup. Defaults to ‘pk’.

  • on_error (Callable[[Type[Model], str, Exception], None] | None) – A callable that will be called if the lookup fails. The callable should accept three arguments: the model class, the value that failed to lookup, and the exception that was raised. If not provided, a CommandError will be raised.

  • return_type (ReturnType) – The model object parser can return types other than the model instance (default) - use the ReturnType enumeration to return other types from the parser including QuerySets or the primitive values of the model fields.

  • case_insensitive (bool)

__init__(model_cls, lookup_field=None, case_insensitive=False, on_error=None, return_type=ReturnType.MODEL_INSTANCE)[source]
Parameters:
convert(value, param, ctx)[source]

Invoke the parsing action on the given string. If the value is already a model instance of the expected type the value will be returned. Otherwise the value will be treated as a value to query against the lookup_field. If no model object is found the error handler is invoked if one was provided.

Parameters:
  • value (Any) – The value to parse.

  • param (Parameter | None) – The parameter that the value is associated with.

  • ctx (Context | None) – The context of the command.

Raises:

CommandError – If the lookup fails and no error handler is provided.

class django_typer.parsers.model.ReturnType(*values)[source]
FIELD_VALUE = 1

Return the value of the field that was matched.

MODEL_INSTANCE = 0

Return the model instance with the matching field value.

QUERY_SET = 2

Return a queryset of model instances that match the field value.