在我使用的 Django 项目中mongoengine
,它为 MongoDB 集合提供了 Django 样式模型。我还使用django-rest-framework-mongoengine
witch extends DRF 来支持Documents
、EmbeddedDocuments
和MongoDBDynamicDocuments
的DynamicEmbeddedDocuments
MongoEngine 模型表示。
而 Django 和 DRF 允许在模型中使用抽象类。现在由 DRF-mongoengine 支持。但是我相信可以通过编写自定义序列化器来添加对抽象模型的支持。
到目前为止,我无法成功,如果您能帮助我实现这一目标,我将不胜感激。
class Entry(Document)
meta = {
'abstract': True,
'allow_inheritance': True,
}
text = StringField()
class Post(Entry)
meta = {
'allow_inheritance': True,
}
class comment(Entry)
meta = {
'allow_inheritance': True,
}
post = ReferenceField(Post) # No Problem serializing this
# for the sake of Demonstration, related is a list of posts and comments
related = ListField(ReferenceField(Entry)) # This is not supported by DRF-mongoengine
class PostSerializer(DocumentSerializer) # Works
class Meta:
model = Post
fields = '__all__'
class PostsViewSet(ModelViewSet):
serializer_class = PostSerializer
queryset = Post.objects.all()
class CommentSerializer(DocumentSerializer) # Fails
class Meta:
model = Comment
fields = '__all__'
class CommentsViewSet(ModelViewSet):
serializer_class = CommentSerializer
queryset = Comment.objects.all()
这是访问该 CommentViewSet 的错误消息的尾部:
File "~/app/venv/lib/python3.9/site-packages/rest_framework_mongoengine/serializers.py", line 345, in get_fields
field_class, field_kwargs = self.build_field(
File "~/app/venv/lib/python3.9/site-packages/rest_framework_mongoengine/serializers.py", line 570, in build_field
child_class, child_kwargs = self.build_field(child_name, info, model_class, nested_depth, embedded_depth)
File "~/app/venv/lib/python3.9/site-packages/rest_framework_mongoengine/serializers.py", line 583, in build_field
return self.build_reference_field(field_name, relation_info, nested_depth)
File "~/app/venv/lib/python3.9/site-packages/rest_framework_mongoengine/serializers.py", line 674, in build_reference_field
related_class = related_model.id.__class__
AttributeError: type object 'AbstractEntityModel' has no attribute 'id'
我目前要做的是为该字段编写一个自定义序列化程序CommentSerializer.related
,我对此有疑问
class RelatedSerializer(DocumentSerializer) # should I use a different parent class?
class Meta:
model = Entry
fields = '__all__'
# What functions should I add here?
# def create(self, data):
# do magic here
# return instance
# def update(self, instance, data):
# do magic here
# return instance
class CommentSerializer(DocumentSerializer) # Fails
class Meta:
model = Comment
fields = '__all__'
related = RelatedSerializer()
这是访问该 CommentViewSet 的错误消息的尾部。
File "~/app/venv/lib/python3.9/site-packages/rest_framework/serializers.py", line 349, in fields
for key, value in self.get_fields().items():
File "~/app/venv/lib/python3.9/site-packages/rest_framework_mongoengine/serializers.py", line 326, in get_fields
self.field_info = get_field_info(model)
File "~/app/venv/lib/python3.9/site-packages/rest_framework_mongoengine/utils.py", line 66, in get_field_info
pk = model._fields[model._meta['id_field']]
KeyError: 'id_field'