It's called models.Model and not models.model (case sensitive). Fix your Poll model like this -

class Poll(models.Model):
    question = models.CharField(max_length=200) 
    pub_date = models.DateTimeField('date published')
Answer from Baishampayan Ghose on Stack Overflow
🌐
Bobby Hadz
bobbyhadz.com › blog › python-attributeerror-module-has-no-attribute
AttributeError: module 'X' has no attribute 'Y' in Python | bobbyhadz
April 8, 2024 - This means that you are either trying to access an attribute that is not present on the module, or you have an incorrect import statement. Consider the following example. We have a module called another_file.py that has an Employee class.
Discussions

class - Python: instance has no attribute - Stack Overflow
There is no motive not to use new style classes, unless yor program needs to run in Python 2.1 ... @martineau: Just check the -I-won't-call-this-a-coincidence question from today: stackoverflow.com/questions/12939288/confusion-with-properties ... Your class doesn't have a __init__(), so by the time it's instantiated, the attribute ... More on stackoverflow.com
🌐 stackoverflow.com
AttributeError: module 'openai.api_resources' has no attribute 'Model'
Hi Guys, I have been working with the openai GPT-3 API in a jupyter notebook for a couple of months now, and suddenly I get the following error message all time, even when running the following simple line of code: AttributeError Traceback (most recent call last) in 6 ---->7 response = ... More on community.openai.com
🌐 community.openai.com
0
1
October 22, 2021
model.fit : AttributeError: 'Model' object has no attribute '_compile_metrics'
Traceback (most recent call last): ... ".../venv/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 2385, in _standardize_user_data metrics=self._compile_metrics, AttributeError: 'Model' object has no attribute '_compile_metrics'... More on github.com
🌐 github.com
2
July 12, 2019
AttributeError: 'module' object has no attribute 'Model'
This is my TensorFlow configuration. tensorflow-gpu 1.5.0 Keras 2.2.4 cuda 8.0 cudnn 6.0 The following error occurred when I tried to run the TensorFlow SSD-mobilenet model. root@VM-0-15-ubuntu:/mi... More on github.com
🌐 github.com
3
October 29, 2018
🌐
Django
code.djangoproject.com › ticket › 13872
#13872 ("AttributeError: 'module' object has no attribute 'day_abbr'" when using Admin to add instance of model with DateField, TimeField, or DateTimeField) – Django
_TimeRE_cache = TimeRE() File "C:\Python25\lib\_strptime.py" in __init__ 191. self.locale_time = LocaleTime() File "C:\Python25\lib\_strptime.py" in __init__ 74. self.__calc_weekday() File "C:\Python25\lib\_strptime.py" in __calc_weekday 94. a_weekday = [calendar.day_abbr[i].lower() for i in range(7)] Exception Type: AttributeError at /admin/foo/bar/add/ Exception Value: 'module' object has no attribute 'day_abbr'
🌐
OpenAI Developer Community
community.openai.com › api
AttributeError: module 'openai.api_resources' has no attribute 'Model' - API - OpenAI Developer Community
October 22, 2021 - Hi Guys, I have been working with the openai GPT-3 API in a jupyter notebook for a couple of months now, and suddenly I get the following error message all time, even when running the following simple line of code: AttributeError Traceback (most recent call last) in 6 ---->7 response = openai.Completion.create(engine=“davinci”, prompt=“This is a test”, max_tokens=5) ~/opt/anaconda3/lib/python3.8/site-packages/openai/api_resources/completion.py in create(cls, t...
🌐
GitHub
github.com › keras-team › keras › issues › 13101
model.fit : AttributeError: 'Model' object has no attribute '_compile_metrics' · Issue #13101 · keras-team/keras
July 12, 2019 - Describe the current behavior The model.fit() function throws a AttributeError: 'Model' object has no attribute '_compile_metrics' exception.
Author   starkgate
Find elsewhere
🌐
GitHub
github.com › tensorflow › tensorflow › issues › 23338
AttributeError: 'module' object has no attribute 'Model' · Issue #23338 · tensorflow/tensorflow
October 29, 2018 - AttributeError: 'module' object has no attribute 'Model'#23338 · Copy link · Assignees · wangyongqi · opened · on Oct 29, 2018 · Issue body actions · This is my TensorFlow configuration. tensorflow-gpu 1.5.0 Keras 2.2.4 cuda 8.0 cudnn 6.0 The following error occurred when I tried to run the TensorFlow SSD-mobilenet model. root@VM-0-15-ubuntu:/mine/models/research# python object_detection/model_main.py --train_dir object_detection/train --pipeline_config_path object_detection/ssd_model/ssd_mobilenet_v1_pets.config /usr/lib/python2.7/dist-packages/matplotlib/init.py:1352: UserWarning: This call to matplotlib.use() has no effect because the backend has already been chosen; matplotlib.use() must be called before pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time.
Author   wangyongqi
🌐
GitHub
github.com › ultralytics › yolov5 › issues › 7151
AttributeError: 'Model' object has no attribute 'get' · Issue #7151 · ultralytics/yolov5
March 26, 2022 - Traceback (most recent call last): File "/workspace/code/test.py", line 314, in <module> test(opt.data, File "/workspace/code/test.py", line 57, in test model = attempt_load(weights, map_location=device) # load FP32 model File "/workspace/code/models/experimental.py", line 120, in attempt_load print(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1177, in __getattr__ raise AttributeError("'{}' object has no attribute '{}'".format( AttributeError: 'Model' object has no attribute 'get' No response ·
Author   falser101
Top answer
1 of 3
6

TLDR: add use_in_migrations = True in your custom managers if you want to do query in migration files

After a few hour of searching i came across this part in the document about model manager and migration

https://docs.djangoproject.com/en/3.2/topics/migrations/#model-managers

For having custom managers in migration, use_in_migrations = True need to be set in the managers so i change my managers to the following:

class StudentManager(models.Manager):
    use_in_migrations = True
    def student_query(self, student):
        return super(StudentManager, self).get_queryset().filter(
            Q(students=student) | Q(course__students=student
        )).distinct('id')


class TeacherManager(models.Manager):
    use_in_migrations = True
    def teacher_query(self, teacher):
        return super(TeacherManager, self).get_queryset().filter(
            Q(teacher=teacher) | Q(course__teacher=teacher)|
            Q(substitute_teacher=teacher)).distinct('id')

class MainCourseClassManager(models.Manager):
    use_in_migrations = True
    
class CourseClass(models.Model):
    class Meta:
        db_table = 'classes'
        verbose_name = _('Class')
        verbose_name_plural = _('Classes')
    
    objects = MainCourseClassManager()
    student_manager = StudentManager()
    teacher_manager = TeacherManager()

And now my migrations work with get_model()

Also noted from the docs

Because it’s impossible to serialize arbitrary Python code, these historical models will not have any custom methods that you have defined. They will, however, have the same fields, relationships, managers (limited to those with use_in_migrations = True) and Meta options (also versioned, so they may be different from your current ones).

2 of 3
0

I have encountered similar problems during custom migrations. I think one of the reasons is the class returned by get_model is sometimes not the full-fledged model class you would get from importing it properly. The get_model call, however, is necessary to make sure the model is properly loaded for the time of the migration. That is because at migration time, the model is supposed to represent the model in its state after the previous migration. I fthe manager was defined at a later time, it will not be there yetOne workaround that works for us:

def update_student(apps, schema_editor):
    _ = apps.get_model('backend', 'CourseClass')  
    # makes sure model is loaded
    from path.to.backend.models import CourseClass
    # gives you the proper class with all utils
    
    # do your thang
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-fix-attributeerror-object-has-no-attribute
How to fix AttributeError: object has no attribute - GeeksforGeeks
August 21, 2024 - In Python 3.x, we use the items() method instead. This article will explain the causes of this error · 2 min read How to Fix "AttributeError: module 'dask.array' has no attribute 'lib'".
🌐
OpenAI Developer Community
community.openai.com › api
AttributeError: type object 'Model' has no attribute 'load' - API - OpenAI Developer Community
January 4, 2023 - I have been working with the openai with python3 and i getting the error: model = openai.Model.load(“text-davinci-002”) AttributeError: type object ‘Model’ has no attribute ‘load’ please how do you resolve this. than…
🌐
Faceswap Forum
forum.faceswap.dev › forum home › support › training support
Help Please! AttributeError: 'Model' object has no attribute 'distribute_strategy' - Faceswap Forum - The place to discuss Faceswap and Deepfakes
December 20, 2020 - 12/20/2020 11:09:51 ERROR Caught ...\MiniConda3\envs\faceswap\lib\site-packages\tensorflow\python\keras\callbacks.py", line 2000, in _get_log_write_dir self.model.distribute_strategy) AttributeError: 'Model' object has no attribute 'distribute_strategy'...
🌐
Codingdeeply
codingdeeply.com › home › troubleshooting: python module has no attribute – tips and solutions
Troubleshooting: Python Module Has No Attribute - Tips and Solutions
February 23, 2024 - If two modules depend on each other, ... tries to access its attribute. Using the wrong import statement to import a module or attribute can cause the “Python Module Has No Attribute” error....
🌐
GitHub
github.com › typeddjango › django-stubs › issues › 83
"Type[Model]" has no attribute "objects" (again?) · Issue #83 · typeddjango/django-stubs
June 1, 2019 - I tried to use your package yesterday and I like it, although I've encountered one issue, when the django model I was accessing had no attribute 'objects', according to mypy. So it's like #16: ... anchor/users/forms.py:26: error: "Type[Model]" has no attribute "objects" anchor/users/views.py:38: error: "Type[Model]" has no attribute "objects" ...
Author   kam1sh
🌐
Containersolutions
containersolutions.github.io › runbooks › posts › python › module-has-no-attribute
Module has no attribute – Runbooks - GitHub Pages
Given the above code a call to foo.bar() within main.py would result in an error about the module ‘foo’ not having the attribute ‘bar’. This is because we have only made the module accessible and not it’s class foo. So to call it we could instead do foo.foo.bar() with the first foo being the module name and the second being the class name. If we change the import from step 1 to instead be from <modulename> import <classname> this will make the class foo directly accessible, eg: # main.py from foo import foo foo.bar() # This now works!
🌐
Django
code.djangoproject.com › ticket › 22033
#22033 ('Model' object has no attribute 'replace') – Django
It's hard to say without seeing your models.py but you most likely have an issue with one of your models' __unicode__ method (or __str__ if you're using Python 3).
🌐
GitHub
github.com › typeddjango › django-stubs › issues › 1754
"type[Model]" has no attribute "objects" error · Issue #1754 · typeddjango/django-stubs
October 4, 2023 - from contextlib import suppress from typing import Type from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model def get_next_pk(model: Type[Model]) -> int: pk = 1 with suppress(ObjectDoesNotExist): pk = model.objects.latest('pk').pk + 1 return pk ... [mypy] python_version = 3.11 plugins = mypy_django_plugin.main, mypy_drf_plugin.main exclude = .git, .idea, .mypy_cache, .ruff_cache, node_modules cache_dir = ./.cache/mypy check_untyped_defs = true disallow_untyped_decorators = true disallow_untyped_calls = true ignore_errors = false ignore_missing_imports = true
Author   jewelvadim
🌐
Django Forum
forum.djangoproject.com › using django › using the orm
Model does not have a attribute called `objects` - Using the ORM - Django Forum
May 16, 2023 - I am trying to use the “objects” attribute that should be available for every model that you create. Unfortunately, if I try to call this attribute, I get an error. views.py file: from django.shortcuts import render from django.http import HttpResponse from store.models import Product def say_hello(request): Product.objects return render(request, 'hello.html', {'name': 'Jonas'}) models.py : from django.db import models class Promotion(models.Model): description = models.Char...