使用django-res -framework的mongo支持模型的可浏览REST api

时间:2021-05-15 19:18:18

I'd like to have a browsable API using django-rest-framework for a rest service using mongodb for the models. Specifically I'd like to be able to have the url pointing to the actual GET method in the listing of all articles.

我希望有一个使用django-res -framework的可浏览API,用于使用mongodb进行模型的rest服务。我特别想让url指向所有文章列表中的实际GET方法。

I have the following model and serializer:

我有以下模型和序列化器:

class Article(mongoengine.Document):
    article_id = mongoengine.StringField(required=True)
    author_id = mongoengine.StringField(required=True)
    content = mongoengine.StringField(required=True)

class ArticleSerializer(serializers.Serializer):
    url = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='article-detail')
    article_id = serializers.CharField(required=True)
    author_id = serializers.CharField(required=True)
    content = serializers.CharField(required=True)

    def restore_object(self, attrs, instance=None):
        if instance is not None:
            for k, v in attrs.iteritems():
                setattr(instance, k, v)
                return instance

        return Article(**attrs)

However when running I get the following error:

然而,当运行时,我得到了以下错误:

AttributeError: 'Article' object has no attribute 'url'

属性错误:'Article'对象没有属性'url'

I tried adding the url attribute to the model but in any case the proper url is not added when the object is serialized. What would the proper use of serializers.HyperlinkedRelatedField for my mongo object Article?

我尝试向模型添加url属性,但在任何情况下,当对象被序列化时,都不会添加正确的url。如何正确使用序列化器。我的mongo对象文章的超链接字段?

Edit:

编辑:

I think that's almost it thanks to Climax. I changed to

我想这多亏了高潮。我改变了

serializers.HyperlinkedIdentityField(view_name='article-detail', lookup_field='article_id')

序列化器。HyperlinkedIdentityField(view_name = article-detail,lookup_field =“article_id”)

but I get

但我得到

{"url": "/article/125/", "article_id": "125"}.

{ " url ":" / / 125 /条”,“article_id”:" 125 " }。

How can I have the DNS name before so that the API is truly browsable? For example:

如何在之前拥有DNS名称,使API真正可浏览?例如:

{"url":"http://example.com:1234/article/125/", "article_id":"125"}

{“url”:“http://example.com:1234 / / 125 /条”,“article_id”:" 125 " }

1 个解决方案

#1


2  

You have to use HyperlinkedIdentityField. Also in this case the relationship is not many in any direction as this serializer is for a single object.

你必须使用HyperlinkedIdentityField。同样,在这种情况下,关系在任何方向上都不是很多,因为这个序列化器只针对一个对象。

url = serializers.HyperlinkedIdentityField(many=False, read_only=True, view_name='article-detail')

#1


2  

You have to use HyperlinkedIdentityField. Also in this case the relationship is not many in any direction as this serializer is for a single object.

你必须使用HyperlinkedIdentityField。同样,在这种情况下,关系在任何方向上都不是很多,因为这个序列化器只针对一个对象。

url = serializers.HyperlinkedIdentityField(many=False, read_only=True, view_name='article-detail')