说我有一个简单的论坛模型:
class User(models.Model):
username = models.CharField(max_length=25)
...
class Topic(models.Model):
user = models.ForeignKey(User)
...
class Post(models.Model):
user = models.ForeignKey(User)
...
Run Code Online (Sandbox Code Playgroud)
现在说我想查看用户子集的每个用户有多少主题和帖子(例如,他们的用户名以"ab"开头).
所以,如果我为每个帖子和主题做一个查询:
User.objects.filter(username_startswith="ab")
.annotate(posts=Count('post'))
.values_list("username","posts")
Run Code Online (Sandbox Code Playgroud)
Yeilds:
[('abe', 5),('abby', 12),...]
Run Code Online (Sandbox Code Playgroud)
和
User.objects.filter(username_startswith="ab")
.annotate(topics=Count('topic'))
.values_list("username","topics")
Run Code Online (Sandbox Code Playgroud)
产量:
[('abe', 2),('abby', 6),...]
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试注释两个以获得一个列表时,我得到一些奇怪的东西:
User.objects.filter(username_startswith="ab")
.annotate(posts=Count('post'))
.annotate(topics=Count('topic'))
.values_list("username","posts", "topics")
Run Code Online (Sandbox Code Playgroud)
产量:
[('abe', 10, 10),('abby', 72, 72),...]
Run Code Online (Sandbox Code Playgroud)
为什么主题和帖子成倍增加?我期待这个:
[('abe', 5, 2),('abby', 12, 6),...]
Run Code Online (Sandbox Code Playgroud)
获得正确列表的最佳方法是什么?
如何构建一个从django获取多行的QuerySet?我认为filter()可以工作,但似乎更糟糕.
例如,我在模型Car中有两行,有两个文本属性(license和vin).现在说我要打印这些车的许可证和酒.我怎么能用一个数据库调用呢?
这是一个可以进行两次数据库调用的答案:
#using get(), two total queries
a = Car.objects.get(id=1) #query here
b = Car.objects.get(id=2) #query here
print(a.license + a.vin) #no query
print(b.license + b.vin) #no query
Run Code Online (Sandbox Code Playgroud)
这显然不起作用,因为我做了两个get()查询.接下来我将尝试filter():
#using filter(), four total queries
c = Car.objects.filter(id__in=(1,2)) #no query
print(c[0].license + c[0].vin) #two queries
print(c[1].license + c[1].vin) #two queries
Run Code Online (Sandbox Code Playgroud)
嗯,这很奇怪,为什么要进行四次数据库调用?有没有办法让它在一个数据库调用中得到两个?
假设我的公司提供一个大型日志文件(4+ GB),其中最新的日志位于顶部.我想构建一个网页来搜索该文件中的关键字"Mike".带宽不是限制,但此网页只能是静态文件(即没有服务器端功能).
示例日志文件:
Joe completed Task 1234 on 2013-10-10
Joe completed Task 1235 on 2013-10-11
Mike completed Task 1236 on 2013-10-11
Joe completed Task 1237 on 2013-10-13
...
Run Code Online (Sandbox Code Playgroud)
显然,我无法将整个文件放入浏览器的内存中,所以我试图找到一种方法来请求文件,在下载数据时搜索数据,然后扔掉不相关的数据以节省内存.我正在使用该xhr.onprogress事件来获取部分下载的日志文件xhr.responseText并进行搜索,但是在读完之后我无法重置responseText.
到目前为止,这是我的算法:
var xhr = new XMLHttpRequest();
xhr.onprogress = function(e){
var cur_len = xhr.responseText.length;
var found_mike = xhr.responseText.indexOf("Mike") != -1 ? true : false;
xhr.responseText = ""; //clear responseText to save memory
console.log("%d - %s - %d", cur_len, found_mike, xhr.responseText.length);
};
xhr.open("get", "mylogfile.txt", true);
xhr.send();
Run Code Online (Sandbox Code Playgroud)
我希望控制台说出类似的东西234343 - …