1
0
mirror of https://github.com/django/django.git synced 2025-03-31 11:37:06 +00:00

allows Fields to be added to Models in __init_subclass__ without affecting existing ModelBase.__new__ API

This commit is contained in:
Jonathan 2023-05-11 11:39:31 +01:00
parent ffff17d4b0
commit a5bec48ab4
2 changed files with 23 additions and 0 deletions

View File

@ -118,6 +118,11 @@ class ModelBase(type):
else:
new_attrs[obj_name] = obj
new_class = super_new(cls, name, bases, new_attrs, **kwargs)
# update contributable_attrs with any such attributes added to new_class - these came from __init_subclass__
for obj_name, obj in dict(vars(new_class)).items():
if _has_contribute_to_class(obj):
contributable_attrs[obj_name] = obj
delattr(new_class, obj_name)
abstract = getattr(attr_meta, "abstract", False)
meta = attr_meta or getattr(new_class, "Meta", None)

View File

@ -249,6 +249,24 @@ class ModelInheritanceTests(TestCase):
self.assertEqual(saved_kwargs, kwargs)
@isolate_apps("model_inheritance")
def test_fields_can_be_added_in_init_subclass(self):
class BaseBookModel(models.Model):
class Meta:
abstract = True
def __init_subclass__(cls, author_model_cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.author = models.ForeignKey(author_model_cls, on_delete = models.CASCADE)
class Author(models.Model):
name = models.CharField(max_length = 256, unique = True)
class Book(BaseBookModel, author_model_cls = Author):
pass
self.assertIsInstance(Book._meta.get_field('author'), models.ForeignKey)
@isolate_apps("model_inheritance")
def test_set_name(self):
class ClassAttr: