Opened 3 years ago

Last modified 5 months ago

#32833 closed Bug

ContentType.objects.get_for_models() in migrations does not works for multiple models — at Version 1

Reported by: HMaker Owned by: nobody
Component: contrib.contenttypes Version: 3.1
Severity: Normal Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by HMaker)

I am trying to use migrations to create default groups, I tried to run the following procedure with migrations.RunPython()

def create_normal_users_group(apps, *args):
    auth = SimpleNamespace(**apps.all_models['auth'])
    myapp = SimpleNamespace(**apps.all_models['myapp'])
    ContentType = apps.get_model('contenttypes', 'ContentType')
    group = auth.group.objects.create(name='Normal Users')
    contenttypes = ContentType.objects.get_for_models(myapp.user, myapp.proxy) # there are more models...
   # ...

but it raises AttributeError

  File "/home/user/projects/myapp/.venv/lib/python3.8/site-packages/django/contrib/contenttypes/models.py", line 89, in get_for_models
    opts_models = needed_opts.pop(ct.model_class()._meta, [])
AttributeError: 'ContentType' object has no attribute 'model_class'

it works when I pass a single model to ContentType.objects.get_for_models(), but get_for_models() is supposed to work with multiple models.

EDIT:
Adding model_class() to ContentType makes it work

def create_normal_users_group(apps, *args):
    auth = SimpleNamespace(**apps.all_models['auth'])
    myapp = SimpleNamespace(**apps.all_models['myapp'])
    ContentType = apps.get_model('contenttypes', 'ContentType')
    # this makes it work =========================
    def model_class(self):
        return apps.get_model(self.app_label, self.model)
    ContentType.model_class = model_class
    # ========================================
    group = auth.group.objects.create(name='Normal Users')
    contenttypes = ContentType.objects.get_for_models(myapp.user, myapp.proxy) # there are more models...
   # ...

Change History (1)

comment:1 by HMaker, 3 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top