2013-07-29 63 views
5

當我嘗試在兩個序列化器之間創建嵌套關係時,出現AttributeError。奇怪的是我正在做與另一個API完全相同的事情,但這一次我沒有得到它的工作。下面是代碼:使用嵌套關係時的AttributeError

class UserSerializer(serializers.ModelSerializer): 

    class Meta: 
     model = get_user_model() 
     fields = ('id', 'last_login','username', 'created') 

class NotificationSerializer(serializers.ModelSerializer): 
    user_id = UserSerializer() 

    class Meta: 
     model = Notification 
     fields = ('id', 'user_id', 'type', 'parent_id', 'created', 'modified', 'seen') 

和相關機型:

class Notification(models.Model): 
    user = models.ForeignKey(User) 
    type = models.CharField(max_length=255) 
    parent_id = models.IntegerField() 
    created = models.DateTimeField(auto_now_add=True) 
    modified = models.DateTimeField(auto_now=True) 
    seen = models.SmallIntegerField(default=0) 

    def __unicode__(self): 
     return self.type 

    class Meta: 
     db_table = 'notification' 

class User(AbstractBaseUser, PermissionsMixin): 
    username = models.CharField(max_length=255, unique=True) 
    id = models.IntegerField(primary_key=True) 
    created = models.DateTimeField(auto_now=True) 
    tag = models.ManyToManyField(Tag) 

    USERNAME_FIELD = 'username' 

    objects = MyUserManager() 

    class Meta: 
     db_table = 'user' 

錯誤:

Exception Type: AttributeError 
Exception Value:  
'long' object has no attribute 'id' 
Exception Location: /lib/python2.7/site-packages/rest_framework/fields.py in get_component, line 55 

誰能幫我這個錯誤?正常的主鍵關係有效,但我肯定希望獲得嵌套關係。

回答

2

由於您的Notification模型有一個名爲user領域,我認爲你應該使用它的user_id

class NotificationSerializer(serializers.ModelSerializer): 
    user = UserSerializer() 

    class Meta: 
     model = Notification 
     fields = ('id', 'user', 'type', 'parent_id', 'created', 'modified', 'seen') 

另一個小紙條是你真的想創建:

id = models.IntegerField(primary_key=True) 

在您的自定義User模型?默認情況下,User模型已經有一個名爲id的字段,它是PK。

+0

謝謝!這是訣竅。 爲什麼使用自定義ID?因爲標準的生成一個自動增量字段,我不想要一個自動增量的id。我手動設置用戶標識(從另一個外部配置文件表)。這就是爲什麼 ;) – Leander