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.

1 Answer 1

2

Since your Notification model has a field called user, I think you should use it instead of user_id:

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

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

Another small note is do you really want to create:

id = models.IntegerField(primary_key=True) 

in your custom User model? By default an User model already has a field called id and it is the PK.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That was the trick. Why a custom id? Because the standard one generates an auto-incremental field and I don't want an auto-incremental id. I set the user ID manually (from another external profiles table). That's why ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.