类型对象'X'没有属性'对象'

Mat*_*day 18 django django-rest-framework

我正在使用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)
Run Code Online (Sandbox Code Playgroud)

serializers.py:

class NotificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Notification
        fields = (
            'type',
            'join_code',
            'requested_userid',
            'datetime_of_notification'
        )
Run Code Online (Sandbox Code Playgroud)

api.py:

class Notification(generics.ListAPIView):
    serializer_class = NotificationSerializer
    def get_queryset(self):
        notifications = Notification.objects.all()
        return notifications
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我解决这个问题吗?它失败api.pynotifications = Notification.objects.all()

Der*_*wok 28

该行notifications = Notification.objects.all()引用了Notificationapi.py中定义的类,而不是models.py.

解决此错误的最简单方法是Notification在api.py或models.py中重命名该类,以便您可以正确引用您的模型.另一种选择是使用命名导入:

from .models import Notification as NotificationModel

class Notification(generics.ListAPIView):
    ...
    def get_queryset(self):
        notifications = NotificationModel.objects.all()
        ...
Run Code Online (Sandbox Code Playgroud)


Pau*_*ett 9

添加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()
Run Code Online (Sandbox Code Playgroud)

  • 有什么解释为什么有时我们需要这样做吗? (2认同)