From 1b535d1076fe99ba7d2e334a179e13efa481d080 Mon Sep 17 00:00:00 2001 From: Rob Percival Date: Fri, 6 May 2022 17:06:34 +0100 Subject: [PATCH] Add GenericModel to types Provides a workaround for a bug in Django that prevents models from inheriting from Generic. --- xocto/types.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/xocto/types.py b/xocto/types.py index 027b5e2..63b98e8 100644 --- a/xocto/types.py +++ b/xocto/types.py @@ -2,7 +2,7 @@ Utility types to save having to redefine the same things over and over. """ -from typing import Generic, NoReturn, Tuple, TypeVar, Union +from typing import TYPE_CHECKING, Generic, NoReturn, Tuple, TypeVar, Union from django.contrib.auth import models as auth_models from django.db import models @@ -63,6 +63,22 @@ class AuthenticatedRequest(HttpRequest, Generic[User]): user: User +# Django does not like models which inherit from Generic. +# This is the recommended workaround (https://code.djangoproject.com/ticket/33174). +if TYPE_CHECKING: + + U = TypeVar("U") + + class GenericModel(models.Model, Generic[U]): + pass + +else: + + class GenericModel(models.Model): + def __class_getitem__(cls, _): # noqa: K106 + return cls + + def assert_never(value: NoReturn) -> NoReturn: """ Helper to ensure checks are exhaustive.