Object type "X" has no attributes "objects"

I am using Django and Django Rest Framework 2.4.0

I get a type object 'Notification' has no attribute 'objects' attribute attribute error type object 'Notification' has no attribute 'objects'

models.py

 class Notification(models.Model): NOTIFICATION_ID = models.AutoField(primary_key=True) user = models.ForeignKey(User, related_name='user_notification') type = models.ForeignKey(NotificationType) join_code = models.CharField(max_length=10, blank=True) requested_userid = models.CharField(max_length=25, blank=True) datetime_of_notification = models.DateTimeField() is_active = models.BooleanField(default=True) 

serializers.py:

 class NotificationSerializer(serializers.ModelSerializer): class Meta: model = Notification fields = ( 'type', 'join_code', 'requested_userid', 'datetime_of_notification' ) 

api.py:

 class Notification(generics.ListAPIView): serializer_class = NotificationSerializer def get_queryset(self): notifications = Notification.objects.all() return notifications 

Can someone help me figure this out? It does not work in api.py on the line notifications = Notification.objects.all()

+16
django django-rest-framework
source share
2 answers

The string notifications = Notification.objects.all() refers to the Notification class defined in api.py, and not to models.py.

The easiest way to fix this error is to rename the Notification class to api.py or models.py so that you can reference your model correctly. Another option is to use named imports:

 from .models import Notification as NotificationModel class Notification(generics.ListAPIView): ... def get_queryset(self): notifications = NotificationModel.objects.all() ... 
+27
source share

Add objects = models.Manager() to your model or any other user manager that you use and / or define.

 class Notification(models.Model): NOTIFICATION_ID = models.AutoField(primary_key=True) user = models.ForeignKey(User, related_name='user_notification') type = models.ForeignKey(NotificationType) join_code = models.CharField(max_length=10, blank=True) requested_userid = models.CharField(max_length=25, blank=True) datetime_of_notification = models.DateTimeField() is_active = models.BooleanField(default=True) objects = models.Manager() 
+7
source share

All Articles