gpt4 book ai didi

django - 类型对象 'X'没有属性 'objects'

转载 作者:行者123 更新时间:2023-12-03 13:21:07 24 4
gpt4 key购买 nike

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

最佳答案

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

关于django - 类型对象 'X'没有属性 'objects',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35543695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com