我正在使用Django和Django Rest Framework 2.4.0
我收到属性错误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
有人可以帮我解决这个问题吗?它在api.py
notifications = Notification.objects.all()
处失败
答案 0 :(得分:27)
第notifications = Notification.objects.all()
行引用了api.py中定义的Notification
类,而不是models.py。
解决此错误的最简单方法是重命名api.py或models.py中的Notification
类,以便您可以正确引用模型。另一种选择是使用命名导入:
from .models import Notification as NotificationModel
class Notification(generics.ListAPIView):
...
def get_queryset(self):
notifications = NotificationModel.objects.all()
...
答案 1 :(得分:4)
将objects = models.Manager()
添加到模型或您正在使用的任何其他管理器中。
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()
答案 2 :(得分:0)
不是这个问题的答案,但是如果您是通过Google来的,则可能不小心将模型标记为抽象,并试图直接对其进行查询,在这种情况下,您需要删除:
class Meta:
abstract = True
答案 3 :(得分:-2)
您可以尝试Model.objects_all.all()