2016-02-21 10 views
6

Sto usando Django Django e Resto Framework 2.4.0tipo di oggetto 'X' non ha nessun attributo 'oggetti'

ottengo l'errore attributo 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 

Qualcuno può aiutarmi a capirlo? Fallisce nel api.py alla linea notifications = Notification.objects.all()

risposta

16

La linea notifications = Notification.objects.all() fa riferimento la classe Notification definito api.py e non models.py.

Il modo più semplice per correggere questo errore è rinominare la classe Notification in api.py o models.py in modo da poter fare riferimento al modello in modo corretto. Un'altra opzione sarebbe quella di utilizzare le importazioni nominate:

from .models import Notification as NotificationModel 

class Notification(generics.ListAPIView): 
    ... 
    def get_queryset(self): 
     notifications = NotificationModel.objects.all() 
     ... 
+0

wohoo! Questo mi ha aiutato a risolvere il mio problema. Grazie! – Lyka