类型对象“ X”没有属性“对象” [英] type object 'X' has no attribute 'objects'
问题描述
我正在使用Django和Django Rest Framework 2.4.0
I am using Django and Django Rest Framework 2.4.0
我遇到了属性错误类型对象'Notification'没有属性'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
有人可以帮我解决这个问题吗?在 api.py
的 notifications = Notification.objects.all()
Can anybody help me to figure this out? It fails in api.py
at the line notifications = Notification.objects.all()
推荐答案
notifications = Notification.objects.all()
行引用了 Notification
类在api.py中定义,而不是在models.py中定义。
The line notifications = Notification.objects.all()
is referencing the Notification
class defined in api.py and not models.py.
解决此错误的最简单方法是重命名api.py或models.py中的 Notification
类以便您可以正确引用模型。另一个选择是使用命名的导入:
The easiest way to fix this error is to rename the Notification
class in either api.py or models.py so that you can refer to your model properly. Another option would be to use named imports:
from .models import Notification as NotificationModel
class Notification(generics.ListAPIView):
...
def get_queryset(self):
notifications = NotificationModel.objects.all()
...
这篇关于类型对象“ X”没有属性“对象”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!