ForeignKey ListField 在 rest_framework 上与 django-nonrel 序列化

ForeignKey ListField serialization on rest_framework with django-nonrel

我有一个 class 叫 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()

视频 属性 是视频的 ListField object ForeignKeys。

当我尝试在 rest_framework 上序列化 Collection object 时,创建我的序列化程序:

class CollectionSerializer(serializers.HyperlinkedModelSerializer):

    videos = VideoSerializer(many=True)

    class Meta:
        model = Collection
        fields = ('name','description','videos', 'pub_date')

但是我得到这个错误:

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

尽管使用了 VideoSerializer 我已经使用了 serializers.StringRelatedField 然后我得到了一个 objectids 的数组作为字符串。但我想要的是序列化器获取 oobjectids 数组并将它们转换为 Vido Objects 并序列化它们。

MongoDB 上的 Object 看起来像这样:

{
    "_id": "ibiza",
    "user_id": {
        "$oid": "5564c86e424f777f81d8f3ec"
    },
    "description": "ertertertre",
    "videos": [
        {
            "$oid": "5564d0c8424f7704aea99813"
        }
    ],
    "pub_date": {
        "$date": "2015-05-27T12:20:57.000Z"
    },
    "name": "Ibiza"
} 

注意: 我想避免使用 EmbeddedModelField

这里的问题是您将字符串(unicode 类型)传递给 DRF,但您希望 DRF 将其转换为嵌套表示。没有任何额外的东西,DRF 不可能做到这一点,因为它超出了它试图维护的一般范围。

另一方面,

Django REST framework Mongoengine 非常适合处理抽象层,建议将 Django REST 框架与 Mongoengine 结合使用。

如果没有抽象层,您将被迫create a custom field将对象 ID 转换为实际对象,然后将它们序列化为嵌套表示。