在Python中获取mongoDB集合中的文档的对象标识 [英] Get object id of document already in mongoDB collection in Python

查看:419
本文介绍了在Python中获取mongoDB集合中的文档的对象标识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mongodb中收集了一个我已经插入文档的集合。现在我要更新一个文档条目,我想在django模板中检索文档ID,就像我在HTML。我想给个别的框一个唯一的id,我打算使用相同的文件id ..所以如何在DJANGO模板中检索文档ID

解决方案

您可以使用 _id 属性获取MongoDB文档的ID。但是,在Django模板中使用 {{object._id}} ,会引起错误,表示找不到_id属性。



要解决这个问题,您必须为应用程序创建一个自定义的模板标签,并使用它来获取_id。



在您的应用文件夹中创建一个templatetags文件夹,并创建一些python文件,例如:appname_tags.py。



目录结构将是这样的

  / projectdir 
/ appdir
/ templatetags
__init__.py
appname_tags.py
models.py
views.py

在appname_tags.py内粘贴以下代码

 从django导入模板
register = template.Library()

@ register.filter(mongo_id)
def mongo_id(value):
return str(value ['_ id'])

现在,您可以通过加载标签mo在模板中使用此新的自定义模板标签dule并将mongo文档对象传递给它。

 < html> 
< body>
{%load appname_tags%}
< p>这里是您的mongodb记录ID:{{object | mongo_id}}< />
< / body>
< / html>

请记住,应用程序应位于 INSTALLED_APPS 设置变量在 settings.py 中为django加载模板标签。


I have a collection in mongodb in which I have already inserted the documents.Now I want to update a document entry and I want to retrieve the document ID in the django template,like I am using checkbox alongside of the entry in the HTML.I want to give individual box a unique id which i plan to use same as the document id .. so HOW DO I RETRIEVE THE DOCUMENT ID IN THE DJANGO TEMPLATE ?

解决方案

You can get the ID of a MongoDB document using the _id attribute. However using {{ object._id }} in a Django template, makes it throw an error saying it couldn't find the _id attribute.

To solve this, you must create a custom template tag for your app and use that to get the _id.

Inside your app folder, create a templatetags folder and create some python file eg:appname_tags.py.

The directory structure would be something like this

/projectdir
  /appdir
    /templatetags
      __init__.py
      appname_tags.py
    models.py
    views.py

Inside the appname_tags.py paste the following code

from django import template
register = template.Library()

@register.filter("mongo_id")
def mongo_id(value):
    return str(value['_id'])

Now you can use this new custom template tag in your templates by loading the tag module and passing the mongo document object to it.

<html>
 <body>
  {% load appname_tags %}
  <p>here is your mongodb record id: {{ object|mongo_id }}</>
 </body>
</html>

Remember, the app should be in the INSTALLED_APPS settings variable in settings.py for django to load the template tag.

这篇关于在Python中获取mongoDB集合中的文档的对象标识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆