Identify the Root Cause
The error arises when the class name used inside the view shadows the actual Django model. In the example, the view class is named Notification, which is the same as the model, so Django interprets Notification as the view class rather than the model when accessing .objects.
Separate Model and View Names
Give the view a distinct name that reflects its purpose. A common convention is to append a suffix such as View or List.
class NotificationListView(generics.ListAPIView):
serializer_class = NotificationSerializer
def get_queryset(self):
return Notification.objects.all()
Correct Import Statements
Ensure the model is imported from the correct module. If the model resides in models.py, import it explicitly:
from .models import Notification
Use get_queryset Properly
Return the queryset directly without assigning it to an intermediate variable unless you need to modify it. This keeps the code concise and avoids accidental name clashes.
def get_queryset(self):
return Notification.objects.filter(is_active=True)
Test and Verify
Run the Django development server and hit the endpoint. If the list appears without errors, the issue is resolved. Use Django's shell to double‑check that Notification.objects.exists() returns a boolean.
Takeaway: Avoid naming the view the same as the model; use clear names and correct imports to eliminate the AttributeError.
People also ask
Why does renaming the view fix the error?
Renaming removes the namespace collision so Django can resolve Notification to the model instead of the view class.
Can I keep the same name if I import the model differently?
Yes, but you must use an alias: from .models import Notification as NotificationModel and refer to NotificationModel.objects.
Inspired by a public discussion on Stack Overflow. This article is an original explanation for learners.