【发布时间】:2014-09-04 19:40:27
【问题描述】:
我使用 Mongoengine 0.8.7 + Django 1.6.5,Mongodb 2.7 我有模特
class Tweet(DynamicDocument):
#user = ReferenceField(User, reverse_delete_rule=CASCADE)
#id = StringField(db_field='id',required=True)
text = StringField(db_field='text', required=True)
lang = StringField(db_field='lang', max_length=200)
slug = StringField(db_field='slug', max_length=200)
retweeted = BooleanField()
#retweet_count = IntField()
text_length = IntField()
date_modified = DateTimeField(default=datetime.now)
is_published = BooleanField(default=True)
tags = ListField(ReferenceField(Tag))
#meta = {'allow_inheritance': False}
def __unicode__(self):
return self.text
def save(self, *args, **kwargs):
self.text_length = len(self.text)
return super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('post-detail', args=[self.id])
def get_edit_url(self):
return reverse('post-update', args=[self.id])
def get_delete_url(self):
return reverse('post-delete', args=[self.id])
在views.py中查看:
class TweetListView(ListView):
model = Tweet
context_object_name = "tweet_list"
def get_template_names(self):
return ["blog/tweet_list.html"]
def get_queryset(self):
tweets = Post.objects
if 'all_posts' not in self.request.GET:
tweets = tweets.filter(text__startswith='RT')
tag = self.request.GET.get('tag', None)
if tag:
tweets = tweets.filter(tags=tag)
#if not tag:
# tweets = tweets.filter(retweeted=True)
return tweets
和模板
{% extends "base.html" %}
{% block content %}
{% for tweet in tweet_list %}
<div style="margin-bottom: 20px;">
<h4>tweet.id: {{ tweet.id }}</h4>
{{ tweet.text|linebreaks }}
tweet.retweeted: {{ tweet.retweeted }}
tweet.created_at: {{ tweet.created_at }}
{% if tweet.tags %}
Tags:
<ul>
{% for tag in tweet.tags %}
<li><a href="?tag={{ tag.id }}">{{ tag }}</a></li>
{% endfor %}
</ul>
{% endif %}
</br>
<a href="{{ tweet.get_absolute_url }}" class="btn btn-small">Read</a>
<a href="{{ tweet.get_edit_url }}" class="btn btn-small">Edit</a>
<a href="{{ tweet.get_delete_url }}" class="btn btn-small">Delete</a>
</div>
{% endfor %}
{% endblock %}
一切正常,推文显示在浏览器中,而我使用过滤器is_published=True,但如果我更改为另一个,它开始抛出错误:
例如我使用:text__startswith='RT'(字段文本),结果:
Exception Value:
id must be an instance of (str, unicode, ObjectId), not <type 'dict'>
Exception Location: D:\WinPython-32bit-2.7.5.1\python-2.7.5\lib\site-packages\bson\objectid.py in __validate, line 203
如果我改成tweets.filter(slug__startswith='RT') 结果:
Exception Value:
Cannot resolve field "slug"
Exception Location: build\bdist.win32\egg\mongoengine\queryset\transform.py in query, line 60
我使用外部脚本挖掘推文,现在想使用 Flask 查询现有集合以在 Web 界面中显示推文。而且我不想在 ORM 中定义所有推文结构。
我有 Robomongo,我看到推文附近的管理帖子手动添加,由 Twitter python 库挖掘。字段被命名为“文本”和“语言”,因为在推文 JSON 中它们的名称相同。 为什么其他字段不起作用?
【问题讨论】:
标签: python django mongodb mongoengine