2013-08-20 75 views
0

一个场在我的模型是一个charField与格式substring1-substring2-substring3-substring4,它可以在此范围值:我需要统计Django的查询集计算子在charField

"1-1-2-1" 
"1-1-2-2" 
"1-1-2-3" 
"1-1-2-4" 
"2-2-2-6" 
"2-2-2-7" 
"2-2-2-9" 
"3-1-1-10" 
"10-1-1-11" 
"11-1-1-12" 
"11-1-1-13" 

例如substring1的单次出现次数。 在这种情况下,有5个独特的事件(1,2,3,10,11)。

"1-X-X-X" 
"2-X-X-X" 
"3-X-X-X" 
"10-X-X-X" 
"11-X-X-XX" 

真诚地,我不知道我可以从哪里开始。我阅读了文档https://docs.djangoproject.com/en/1.5/ref/models/querysets/,但我没有找到具体的线索。

在此先感谢。

+0

你能解释一下好吗?从你的例子中,'子串1'(根据你的规则,是数字'1')出现4次(1,2,3和4项),所以我真的不知道你有5和与那些职位 –

+0

对不起!我只是修改它。我的意思是计算作为charfield的第一部分(例如NN-)的substring1的唯一出现次数。 在这种情况下,有5个唯一的事件1,2,3,10,11 – Daviddd

+0

好吧,现在我明白你的问题了,你想为你的字符串的第一个子字符串计算唯一的外观。现在它是有道理:) –

回答

1
results = MyModel.objects.all() 

pos_id = 0 

values_for_pos_id = [res.field_to_check.split('-')[pos_id] for res in results] 
values_for_pos_id = set(values_for_pos_id) 

这是如何工作的:

  • 首先你抓取所有对象(results
  • pos_id是你的子指数(你有4子,因此它在范围0〜3)
  • 你在-(你的分隔符)上分割了每个field_to_check(又名:你在哪里存储子串组合)并获取该对象的正确子串
  • 你的列表转换为一组(将所有的唯一值)

那么简单len(values_for_pos_id)会做的伎俩为

您注意:如果你没有pos_id或根本不能将它设置在任何地方,你只需要像这样循环:

for pos_id in range(4): 
    values_for_pos_id = set([res.field_to_check.split('-')[pos_id] for res in results]) 
    # process your set results now 
    print len(values_for_pos_id) 
+0

只需最好(cit。)! 感谢您的代码解释! – Daviddd

0

尝试这样的事情...

# Assumes your model name is NumberStrings and attribute numbers stores the string. 
search_string = "1-1-2-1" 
matched_number_strings = NumberStrings.objects.filter(numbers__contains=search_string) 
num_of_occurrences = len(matches_found) 
matched_ids = [match.id for match in matched_number_strings] 
+0

对不起,我的问题不清楚。我没有输入搜索字符串。我需要计算substring1的所有唯一出现次数。看到我修改后的问题。 – Daviddd

0

,你可以通过这些项目(我猜他们是字符串),并且每个substring_ ñ的价值添加到SET_ ñ循环。

由于设定值是唯一的,因此您将拥有一个名为Set_1的集合,例如包含1,2,3,10,11。

有意义吗?