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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With