我想从教育问题记录列表中筛选出一些常见的标签组合。Django Queryset:需要帮助优化这组查询
对于这个例子,我只看到2个标签的例子(标签标签),我应该得到如下结果的例子: “point”+“curve”(65个条目) “add”+ “减”(40项) ...
这是在SQL语句期望的结果:
SELECT a.tag, b.tag, count(*)
FROM examquestions.dbmanagement_tag as a
INNER JOIN examquestions.dbmanagement_tag as b on a.question_id_id = b.question_id_id
where a.tag != b.tag
group by a.tag, b.tag
基本上,我们正在与常见问题不同的标签被识别成一个列表,并在其中组相同的匹配标签组合。
我曾尝试使用Django的查询集做一个类似的查询:
twotaglist = [] #final set of results
alphatags = tag.objects.all().values('tag', 'type').annotate().order_by('tag')
betatags = tag.objects.all().values('tag', 'type').annotate().order_by('tag')
startindex = 0 #startindex reduced by 1 to shorten betatag range each time the atag changes. this is to reduce the double count of comparison of similar matches of tags
for atag in alphatags:
for btag in betatags[startindex:]:
if (atag['tag'] != btag['tag']):
commonQns = [] #to check how many common qns
atagQns = tag.objects.filter(tag=atag['tag'], question_id__in=qnlist).values('question_id').annotate()
btagQns = tag.objects.filter(tag=btag['tag'], question_id__in=qnlist).values('question_id').annotate()
for atagQ in atagQns:
for btagQ in btagQns:
if (atagQ['question_id'] == btagQ['question_id']):
commonQns.append(atagQ['question_id'])
if (len(commonQns) > 0):
twotaglist.append({'atag': atag['tag'],
'btag': btag['tag'],
'count': len(commonQns)})
startindex=startindex+1
逻辑工作正常,但是我非常新的这个平台,我不知道如果有一个更短的解决办法,而不是使其效率更高。
目前,查询所需的约5K X 5K标记比较:(
附加组件约45秒:Tag类
class tag(models.Model):
id = models.IntegerField('id',primary_key=True,null=False)
question_id = models.ForeignKey(question,null=False)
tag = models.TextField('tag',null=True)
type = models.CharField('type',max_length=1)
def __str__(self):
return str(self.tag)
您的模型与我的有所不同,因此我无法实现您的解决方案。我只是编辑了问题并添加了Tag类。你认为你可以提供一个解决方案吗?尽管如此,非常感谢您的建议,但是这种模式对我的所有其他代码都会产生太大的影响。我会牢记在将来使用它:) – jdtoh
@jdtoh你可以请你也用你的'问题'模型编辑你的问题吗?从我所看到的,我的解决方案应该仍然适合你。外键有一个“反向关系”,这意味着你可以通过'question.objects.tag_set.all()'''''''''''''''''''作为一个集合来访问'tags'。另外,模型名称通常以大写字母开头。 –
@jdtoh看到我的编辑,它应该用你定义的模型解决你的问题。 –