I have a class called Collection
class Collection(models.Model):
slug = models.CharField(max_length=32, primary_key=True)
name = models.CharField(max_length=200)
description = models.TextField()
user = models.ForeignKey(User)
videos = ListField(models.ForeignKey(Video))
pub_date = models.DateTimeField('date published')
objects = MongoDBManager()
with a videos property that is a ListField of Video object ForeignKeys.
When I try to Serialize Collection object on rest_framework y create my serializer:
class CollectionSerializer(serializers.HyperlinkedModelSerializer):
videos = VideoSerializer(many=True)
class Meta:
model = Collection
fields = ('name','description','videos', 'pub_date')
But i get this error:
Got AttributeError when attempting to get a value for field `name` on serializer `VideoSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `unicode` instance.
Original exception text was: 'unicode' object has no attribute 'name'.
Despite using VideoSerializer i have used serializers.StringRelatedField and then I get an array of objectids as strings. But what I want is the serializer to get that array of oobjectids and convert them to Vido Objects and serialize them.
The Object on MongoDB looks like this:
{
"_id": "ibiza",
"user_id": {
"$oid": "5564c86e424f777f81d8f3ec"
},
"description": "ertertertre",
"videos": [
{
"$oid": "5564d0c8424f7704aea99813"
}
],
"pub_date": {
"$date": "2015-05-27T12:20:57.000Z"
},
"name": "Ibiza"
}
NOTE: I want to avoid using EmbeddedModelField
The issue here is that you are passing a string (unicode
type) to DRF but you are expecting DRF to turn it into a nested representation. Without anything extra, DRF is not possible to do this, as it's way out of the general scope that it tries to maintain.
Django REST framework Mongoengine on the other hand is perfectly fine with handling the abstraction layer, and it's recommended for those using Django REST framework with Mongoengine.
Without an abstraction layer, you are going to be forced to create a custom field that converts the object ids into the actual objects, and then serializes them into the nested representations.