【问题标题】:type object 'X' has no attribute 'objects'类型对象“X”没有属性“对象”
【发布时间】:2016-06-03 07:00:52
【问题描述】:

我正在使用 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() 行失败

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    notifications = Notification.objects.all() 行引用了 api.py 中定义的 Notification View 类,而不是 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()
            ...
    

    【讨论】:

    • 哇!这帮助我解决了我的问题。谢谢!
    【解决方案2】:

    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()
    

    【讨论】:

    • objects = models.Manager() 优秀
    • 任何解释为什么有时我们需要这样做?
    • 核心问题是Derek Kwok提到的。当我回答这个问题时,我错过了。但他是对的,问题在于models.py 和views.py 中的Notification 类名重复。除非您想定义自定义管理器,否则不必定义 objects 变量。
    【解决方案3】:

    不是这个问题的答案,但如果你是通过谷歌来的,你可能不小心将你的模型标记为抽象并试图直接查询它,在这种情况下你需要删除:

        class Meta:
            abstract = True
    

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多