5

I'm getting an AttributeError when I try to create a nested relation between two serializers. The weird thing is that I'm doing exactly the same thing as with another API, but this time I don't get it working. Here is the code:

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

And the associated models:

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'

The error:

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

Can anyone help me with this error? A normal primary key relationship works, but I would definitely like to get a nested relationship.

4

1 回答 1

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。

于 2013-07-29T23:09:19.720 回答