Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError when using nested relations

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.

like image 856
Leander Avatar asked Nov 02 '22 17:11

Leander


1 Answers

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.

like image 175
Hieu Nguyen Avatar answered Nov 11 '22 16:11

Hieu Nguyen