KeyError: '__module__' when creating dynamically proxy models

I want to create dynamically proxy models with this code:

from django.db import models
class BaseId(models.Model):
    def __str__(self):
        return self.nom
    class Meta:
        app_label = 'sae'
        abstract = True
NOMENCL_LIST = ['CAT', 'CATR', 'CCR', 'ESPIC', 'GRP', 'MFT', 'NAT', 'PERSO', 'STJ', 'STJR']
class Nomenclature(BaseId):
    code = models.CharField(max_length=20, unique=True)
    nom = models.CharField( max_length=250)
    
class Valeurs_nomenclature(BaseId):
    nomenclature = models.ForeignKey(Nomenclature, on_delete=models.PROTECT, related_name='valeurs')
    code = models.CharField(max_length=20)
    nom = models.CharField(max_length=250)

class NomenclatureManager(models.Manager):
    def get_queryset(self):
        qs = super().get_queryset()
        return qs.filter(nomenclature__code=qs.model.__name__)

for nomencl in NOMENCL_LIST:
    if nomencl not in globals():
        meta = type('Meta', (BaseId.Meta,), { 'proxy':True })
        model = type(nomencl, (Valeurs_nomenclature,), # this line causes the error
                                { 'Meta':meta, 'objects':NomenclatureManager })
        globals()[nomencl] = model

This code raises a KeyError the before last line:

module = attrs.pop("__module__")
KeyError: '__module__'

When I set explicitly "module", it works :

model = type(nomencl, (Valeurs_nomenclature,),
            { 'Meta':meta, 'objects':NomenclatureManager, '__module__':'sae.models.id_models' })

My question: in what circumstance 'module' is set implicitly or not ?

Back to Top