def _get_serializers_to_check(
    include_apps: Optional[Iterable[str]] = None,
) -> Tuple[Iterator[Type[Serializer]], Iterator[Type[ModelSerializer]]]:
    serializer_classes = _filter_app_serializers(
        _collect_serializers(s for s in Serializer.__subclasses__()
                             if s is not ModelSerializer  # type: ignore
                             ),
        include_apps,
    )
    model_serializer_classes = _filter_app_serializers(
        _collect_serializers(ModelSerializer.__subclasses__()), include_apps)
    return (
        serializer_classes,
        cast(Iterator[Type[ModelSerializer]], model_serializer_classes),
    )
Esempio n. 2
0
def check_serializers(app_configs, **kwargs):
    import inspect
    from rest_framework.serializers import ModelSerializer
    import conf.urls  # noqa, force import of all serializers.

    for serializer in ModelSerializer.__subclasses__():

        # Skip third-party apps.
        path = inspect.getfile(serializer)
        if path.find("site-packages") > -1:
            continue

        if hasattr(serializer.Meta, "read_only_fields"):
            continue

        yield django.core.checks.Warning(
            "ModelSerializer must define read_only_fields.",
            hint="Set read_only_fields in ModelSerializer.Meta",
            obj=serializer,
            id="H300",
        )
Esempio n. 3
0
def check_serializers(app_configs, **kwargs):
    """
    Custom checker for validating that all serializers have set read_only_fields.

    If all fields are available for write, then read_only_fields should be an empty tuple.

    Read_only serializers have a much better performance.

    Source: https://hakibenita.com/django-rest-framework-slow
    """

    import inspect
    from rest_framework.serializers import ModelSerializer
    import sys

    # Sometimes devs have not set up their IDE when optimizing imports
    # so the import could be accidentally removed, which will not import the serializers then.
    # Hence, we check if the module has been imported.
    if "tsg.urls" not in sys.modules:
        raise ValueError(
            "tsg.urls has not been imported! Likely it has been removed by your IDE when formatting the file?"
        )

    for serializer in ModelSerializer.__subclasses__():

        # Skip third-party apps.
        path = inspect.getfile(serializer)
        if path.find("site-packages") > -1:
            continue

        if hasattr(serializer.Meta, "read_only_fields"):
            continue

        yield django.core.checks.Warning(
            "ModelSerializer must define read_only_fields.",
            hint="Set read_only_fields in ModelSerializer.Meta",
            obj=serializer,
            id="H300",
        )