Skip to content

Django Project Cruddals

A base class for defining GraphQL schemas for a Django project using Cruddals.

This class provides methods to dynamically create GraphQL schemas for each app in the project based on provided settings.

This class is a wrapper around DjangoAppCruddals to generate GraphQL schema for each app in the project, avoiding the need to define a subclass for each app. Otherwise this approach yet allow customizing the behavior of the generated GraphQL schema for each app with the same attributes as DjangoAppCruddals but in a dictionary format.

Attributes:

Name Type Description
apps Union[Literal['__all__'], Tuple[str, ...]]

Names of Django apps for which schemas will be generated. Defaults to "all", meaning all apps in the project.

schema Schema

The generated GraphQL schema for the project.

Query TypeAlias

The combined Query object for the project.

Mutation TypeAlias

The combined Mutation object for the project.

meta

A dictionary with the name of the apps as keys and the generated classes as values.

To use this class, define a subclass and include a Meta class with the required attributes.

Example Usage:

from graphene_django_cruddals import DjangoProjectCruddals

class YourProjectCruddals(DjangoProjectCruddals):
    class Meta:
        apps = "__all__"
from graphene_django_cruddals import DjangoProjectCruddals

class YourProjectCruddals(DjangoProjectCruddals):
    class Meta:
        apps = ("your_app1", "your_app2")
        # exclude_apps = ("your_app1",)
        cruddals_interfaces = (CustomCruddalsInterface,)
        # exclude_cruddals_interfaces = ("CustomCruddalsInterface",)
        settings_for_app = {
            "your_app1": {
                "models": ("YourModel1", "YourModel2"),
                # "exclude_models": ("YourModel1",),
                "prefix": "New",
                "suffix": "Suffix",
                "cruddals_interfaces": (CustomCruddalsInterfaceForYourApp1,),
                # "exclude_cruddals_interfaces": ("CustomCruddalsInterface",),
                "functions": ("create", "read", "update", "delete", "deactivate", "activate", "list", "search"),
                # "exclude_functions": ("create",),
                "settings_for_model": {
                    "YourModel1": {
                        "functions": ("create", "read", "update", "delete", "deactivate", "activate", "list", "search"),
                        # "exclude_functions": ("create",),
                        "prefix": "New",
                        "suffix": "Suffix",
                        "cruddals_interfaces": (CustomCruddalsInterfaceForYourModel1,),
                        # "exclude_cruddals_interfaces": ("CustomCruddalsInterface",),
                        "field_for_activate_deactivate": "is_enabled",
                    },
                    "YourModel2": {
                        # ...
                    },
                },
            },
            "your_app2": {
                # ...
            },
        }

Meta Class Options:

Note

These options can also be seen below in the definition of __init_subclass_with_meta__ method.

*apps (Union[Literal["__all__"], Tuple[str, ...]]):* Names of Django apps for which schemas will be generated. Defaults to "__all__", meaning all apps in the project.
*exclude_apps (Tuple[str, ...]):* Names of apps to exclude from schema generation. Defaults to ().
*cruddals_interfaces (Tuple[Type[Any], ...], optional):* A tuple of additional Cruddals interfaces to be implemented by the generated GraphQL Schema. Defaults to ().
*settings_for_app (Dict[str, Any], optional):* A dictionary with the name of the apps as keys and a dictionary with the settings for each app as values for overriding the default settings of the generated GraphQL Schema. Defaults to {}.
*functions (Tuple[FunctionType, ...], optional):* Functions to include in the schemas can be "create", "read", "update", "delete", "deactivate", "activate", "list", "search" .
*exclude_functions (Tuple[FunctionType, ...], optional):* Functions to exclude from schema generation. Defaults to ().
Source code in graphene_django_cruddals/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
class DjangoProjectCruddals(SubclassWithMeta):
    """
    A base class for defining GraphQL schemas for a **Django project** using Cruddals.

    This class provides methods to dynamically create GraphQL schemas for each app in the project based on provided settings.

    This class is a wrapper around `DjangoAppCruddals` to generate GraphQL schema for each app in the project, avoiding the need to define a subclass for each app.
    Otherwise this approach yet allow customizing the behavior of the generated GraphQL schema for each app with the same attributes as `DjangoAppCruddals` but in a dictionary format.

    Attributes:
        apps (Union[Literal["__all__"], Tuple[str, ...]]): Names of Django apps for which schemas will be generated. Defaults to "__all__", meaning all apps in the project.
        schema: The generated GraphQL schema for the project.
        Query: The combined Query object for the project.
        Mutation: The combined Mutation object for the project.
        meta: A dictionary with the name of the apps as keys and the generated classes as values.

    To use this class, define a subclass and include a `Meta` class with the required attributes.

    Example Usage:
    --------------

    === "Only Required Arguments"

        ```python
        from graphene_django_cruddals import DjangoProjectCruddals

        class YourProjectCruddals(DjangoProjectCruddals):
            class Meta:
                apps = "__all__"
        ```
    === "With Optional Arguments"

        ```python
        from graphene_django_cruddals import DjangoProjectCruddals

        class YourProjectCruddals(DjangoProjectCruddals):
            class Meta:
                apps = ("your_app1", "your_app2")
                # exclude_apps = ("your_app1",)
                cruddals_interfaces = (CustomCruddalsInterface,)
                # exclude_cruddals_interfaces = ("CustomCruddalsInterface",)
                settings_for_app = {
                    "your_app1": {
                        "models": ("YourModel1", "YourModel2"),
                        # "exclude_models": ("YourModel1",),
                        "prefix": "New",
                        "suffix": "Suffix",
                        "cruddals_interfaces": (CustomCruddalsInterfaceForYourApp1,),
                        # "exclude_cruddals_interfaces": ("CustomCruddalsInterface",),
                        "functions": ("create", "read", "update", "delete", "deactivate", "activate", "list", "search"),
                        # "exclude_functions": ("create",),
                        "settings_for_model": {
                            "YourModel1": {
                                "functions": ("create", "read", "update", "delete", "deactivate", "activate", "list", "search"),
                                # "exclude_functions": ("create",),
                                "prefix": "New",
                                "suffix": "Suffix",
                                "cruddals_interfaces": (CustomCruddalsInterfaceForYourModel1,),
                                # "exclude_cruddals_interfaces": ("CustomCruddalsInterface",),
                                "field_for_activate_deactivate": "is_enabled",
                            },
                            "YourModel2": {
                                # ...
                            },
                        },
                    },
                    "your_app2": {
                        # ...
                    },
                }
        ```

    Meta Class Options:
    -------------------

    Note:
        These options can also be seen below in the definition of `__init_subclass_with_meta__` method.

    ```markdown
    *apps (Union[Literal["__all__"], Tuple[str, ...]]):* Names of Django apps for which schemas will be generated. Defaults to "__all__", meaning all apps in the project.
    *exclude_apps (Tuple[str, ...]):* Names of apps to exclude from schema generation. Defaults to ().
    *cruddals_interfaces (Tuple[Type[Any], ...], optional):* A tuple of additional Cruddals interfaces to be implemented by the generated GraphQL Schema. Defaults to ().
    *settings_for_app (Dict[str, Any], optional):* A dictionary with the name of the apps as keys and a dictionary with the settings for each app as values for overriding the default settings of the generated GraphQL Schema. Defaults to {}.
    *functions (Tuple[FunctionType, ...], optional):* Functions to include in the schemas can be "create", "read", "update", "delete", "deactivate", "activate", "list", "search" .
    *exclude_functions (Tuple[FunctionType, ...], optional):* Functions to exclude from schema generation. Defaults to ().
    ```

    """

    apps: Union[Literal["__all__"], Tuple[str, ...]] = "__all__"
    schema: graphene.Schema

    Query: TypeAlias = "graphene.ObjectType"
    Mutation: TypeAlias = "graphene.Mutation"

    meta = None

    @classmethod
    def __init_subclass_with_meta__(
        cls,
        apps: Union[Literal["__all__"], Tuple[str, ...]] = "__all__",
        exclude_apps: Tuple[str, ...] = (),
        cruddals_interfaces: Tuple[str, ...] = (),
        settings_for_app: Optional[Dict[str, Any]] = None,
        functions: Tuple[str, ...] = (),
        exclude_functions: Tuple[str, ...] = (),
        **kwargs: Any,
    ):
        """
        Initialize the subclass with meta settings and dynamically create GraphQL schemas for apps.

        Args:
            apps (str or tuple): Names of Django apps for which schemas will be generated.
                Defaults to "__all__", meaning all apps in the project.
            exclude_apps (tuple): Names of apps to exclude from schema generation.
            cruddals_interfaces (tuple): Additional GraphQL cruddals_interfaces to include in the schemas.
            settings_for_app (dict): Settings specific to each app for schema generation.
            functions (tuple): Functions to include in the schemas can be "create", "read", "update", "delete", "deactivate", "activate", "list", "search" .
            exclude_functions (tuple): Functions to exclude from schema generation.
            **kwargs: Additional keyword arguments.
        """
        cls.apps = apps
        if settings_for_app is None:
            settings_for_app = {}

        default_exclude_apps = (
            "graphene_django",
            "messages",
            "staticfiles",
            "corsheaders",
            "new_cruddals_django",
        )
        exclude_apps = exclude_apps + default_exclude_apps

        interfaces_for_project = cruddals_interfaces

        apps_name = cls._get_apps_name(apps, exclude_apps)
        cls._validate_apps(apps_name)
        cls._validate_apps(settings_for_app.keys())

        queries = ()
        mutations = ()

        for _app_name in apps_name:
            settings_of_app = settings_for_app.get(_app_name, {})

            final_models, final_exclude_models = cls._get_final_models(
                apps, _app_name, settings_of_app
            )
            final_interfaces, final_exclude_interfaces = cls._get_final_interfaces(
                interfaces_for_project, settings_of_app
            )
            final_functions, final_exclude_functions = cls._get_final_functions(
                functions, exclude_functions, settings_of_app
            )

            final_settings_for_model = settings_of_app.get("settings_for_model", {})

            AppSchema = cls._create_app_schema(
                _app_name,
                final_models,
                final_exclude_models,
                final_interfaces,
                final_exclude_interfaces,
                final_functions,
                final_exclude_functions,
                final_settings_for_model,
            )

            queries = queries + (AppSchema.Query,)
            if AppSchema.Mutation:
                mutations = mutations + (AppSchema.Mutation,)

        cls.schema, cls.Query, cls.Mutation = get_schema_query_mutation(
            queries, {}, mutations, {}
        )  # type: ignore

        super().__init_subclass_with_meta__(**kwargs)

    @classmethod
    def _get_apps_name(cls, apps, exclude_apps):
        apps_name = ()
        if apps == "__all__":
            apps_name = django_apps.app_configs.keys()
        elif isinstance(apps, tuple):
            apps_name = apps
        else:
            raise ValueError("apps should be '__all__' or tuple")

        apps_name = [item for item in apps_name if item not in exclude_apps]
        return apps_name

    @classmethod
    def _validate_apps(cls, apps_name):
        [django_apps.get_app_config(app_name) for app_name in apps_name]

    @classmethod
    def _get_final_models(cls, apps, _app_name, settings_of_app):
        exclude_models = settings_of_app.get("exclude_models", None)
        if exclude_models is None:
            _models = apps.get(_app_name, None) if isinstance(apps, dict) else None
            return (settings_of_app.get("models", _models), None)
        else:
            return (None, exclude_models)

    @classmethod
    def _get_final_interfaces(cls, interfaces_for_project, settings_of_app):
        interfaces_for_app = settings_of_app.get("cruddals_interfaces", ())
        return (
            interfaces_for_project + interfaces_for_app,
            settings_of_app.get("exclude_cruddals_interfaces", ()),
        )

    @classmethod
    def _get_final_functions(cls, functions, exclude_functions, settings_of_app):
        functions_of_app = settings_of_app.get("functions", ())
        exclude_functions_of_app = settings_of_app.get("exclude_functions", ())
        return (
            functions + functions_of_app,
            exclude_functions + exclude_functions_of_app,
        )

    @classmethod
    def _create_app_schema(
        cls,
        _app_name,
        final_models,
        final_exclude_models,
        final_interfaces,
        exclude_interfaces_of_app,
        final_functions,
        final_exclude_functions,
        final_settings_for_model,
    ):
        MetaAppCruddals = build_class(
            name="Meta",
            attrs={
                "app_name": _app_name,
                "models": final_models,
                "exclude_models": final_exclude_models,
                "cruddals_interfaces": final_interfaces,
                "exclude_cruddals_interfaces": exclude_interfaces_of_app,
                "functions": final_functions,
                "exclude_functions": final_exclude_functions,
                "settings_for_model": final_settings_for_model,
            },
        )
        AppCruddals = build_class(
            name=f"{_app_name}AppCruddals",
            bases=(DjangoAppCruddals,),
            attrs={"Meta": MetaAppCruddals},
        )

        if cls.meta is None:
            cls.meta = {_app_name: AppCruddals}
        else:
            cls.meta.update({_app_name: AppCruddals})
        return AppCruddals

__init_subclass_with_meta__ classmethod

__init_subclass_with_meta__(
    apps="__all__",
    exclude_apps=(),
    cruddals_interfaces=(),
    settings_for_app=None,
    functions=(),
    exclude_functions=(),
    **kwargs
)

Initialize the subclass with meta settings and dynamically create GraphQL schemas for apps.

Parameters:

Name Type Description Default
apps str or tuple

Names of Django apps for which schemas will be generated. Defaults to "all", meaning all apps in the project.

'__all__'
exclude_apps tuple

Names of apps to exclude from schema generation.

()
cruddals_interfaces tuple

Additional GraphQL cruddals_interfaces to include in the schemas.

()
settings_for_app dict

Settings specific to each app for schema generation.

None
functions tuple

Functions to include in the schemas can be "create", "read", "update", "delete", "deactivate", "activate", "list", "search" .

()
exclude_functions tuple

Functions to exclude from schema generation.

()
**kwargs Any

Additional keyword arguments.

{}
Source code in graphene_django_cruddals/main.py
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
@classmethod
def __init_subclass_with_meta__(
    cls,
    apps: Union[Literal["__all__"], Tuple[str, ...]] = "__all__",
    exclude_apps: Tuple[str, ...] = (),
    cruddals_interfaces: Tuple[str, ...] = (),
    settings_for_app: Optional[Dict[str, Any]] = None,
    functions: Tuple[str, ...] = (),
    exclude_functions: Tuple[str, ...] = (),
    **kwargs: Any,
):
    """
    Initialize the subclass with meta settings and dynamically create GraphQL schemas for apps.

    Args:
        apps (str or tuple): Names of Django apps for which schemas will be generated.
            Defaults to "__all__", meaning all apps in the project.
        exclude_apps (tuple): Names of apps to exclude from schema generation.
        cruddals_interfaces (tuple): Additional GraphQL cruddals_interfaces to include in the schemas.
        settings_for_app (dict): Settings specific to each app for schema generation.
        functions (tuple): Functions to include in the schemas can be "create", "read", "update", "delete", "deactivate", "activate", "list", "search" .
        exclude_functions (tuple): Functions to exclude from schema generation.
        **kwargs: Additional keyword arguments.
    """
    cls.apps = apps
    if settings_for_app is None:
        settings_for_app = {}

    default_exclude_apps = (
        "graphene_django",
        "messages",
        "staticfiles",
        "corsheaders",
        "new_cruddals_django",
    )
    exclude_apps = exclude_apps + default_exclude_apps

    interfaces_for_project = cruddals_interfaces

    apps_name = cls._get_apps_name(apps, exclude_apps)
    cls._validate_apps(apps_name)
    cls._validate_apps(settings_for_app.keys())

    queries = ()
    mutations = ()

    for _app_name in apps_name:
        settings_of_app = settings_for_app.get(_app_name, {})

        final_models, final_exclude_models = cls._get_final_models(
            apps, _app_name, settings_of_app
        )
        final_interfaces, final_exclude_interfaces = cls._get_final_interfaces(
            interfaces_for_project, settings_of_app
        )
        final_functions, final_exclude_functions = cls._get_final_functions(
            functions, exclude_functions, settings_of_app
        )

        final_settings_for_model = settings_of_app.get("settings_for_model", {})

        AppSchema = cls._create_app_schema(
            _app_name,
            final_models,
            final_exclude_models,
            final_interfaces,
            final_exclude_interfaces,
            final_functions,
            final_exclude_functions,
            final_settings_for_model,
        )

        queries = queries + (AppSchema.Query,)
        if AppSchema.Mutation:
            mutations = mutations + (AppSchema.Mutation,)

    cls.schema, cls.Query, cls.Mutation = get_schema_query_mutation(
        queries, {}, mutations, {}
    )  # type: ignore

    super().__init_subclass_with_meta__(**kwargs)