作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试选择 3 个最近发布的项目,其中任何标签都与当前项目相似(以及其他一些过滤器)找不到有效的方法,数据库中有很多“项目”。
from taggit_autosuggest.managers import TaggableManager
class Item(models.Model):
publish_date = DateField()
tags = TaggableManager()
sites = ManyToManyField(Site)
def my_view():
...
current_item = #get current item
related_items = Item.active_objects.filter(
sites=current_site,
id__in=[x.id for x in current_item.tags.similar_objects()]
).order_by('-publish_date')[:3]
...
但这会导致相当大的性能问题,来自 similar_objects() 方法。 current_item 拥有的标签越多,指数越差
# Query_time: 20.613503 Lock_time: 0.000182 Rows_sent: 83 Rows_examined: 7566504
SELECT `taggit_taggeditem`.`content_type_id`, `taggit_taggeditem`.`object_id`, COUNT(`taggit_taggeditem`.`id`) AS `n` FROM `taggit_taggeditem` WHERE (NOT (`taggit_taggeditem`.`object_id` = 205636 AND `taggit_taggeditem`.`content_type_id`
= 11 ) AND (`taggit_taggeditem`.`tag_id`) IN (SELECT DISTINCT `taggit_tag`.`id` FROM `taggit_tag` INNER JOIN `taggit_taggeditem` ON ( `taggit_tag`.`id` = `taggit_taggeditem`.`tag_id` ) WHERE (`taggit_taggeditem`.`object_id` = 205636 AND
`taggit_taggeditem`.`content_type_id` = 11 ))) GROUP BY `taggit_taggeditem`.`content_type_id`, `taggit_taggeditem`.`object_id` ORDER BY `n` DESC;
我也试过不使用相似对象方法
related_items = Item.active_objects.filter(
sites=current_site,
tags__in=current_item.tags.all()).exclude(slug=slug).order_by('-publish_date').distinct()[:3]
context['tagged'] = tags.order_by('-publish_date').distinct()[:3]
这一直很糟糕(有些查询长达 120 秒,糟糕)
执行此操作的“好”方法是什么?!
最佳答案
我的假设是获取标签并使用标签-> 项目关系比搜索所有项目更有效。所以我们构建了一个包含所有 TaggedItem 的查询集,获取所有对象的 ID,然后执行我们的过滤器。
from taggit.models import TaggedItem
related_items = TaggedItem.objects.none()
for tag in current_item.tags.all():
#build queryset of all TaggedItems
related_items |= tag.taggit_taggeditem_items.all()
#TaggedItem doesn't have a direct link to the object, have to grab ids
ids = related_items.values_list('object_id', flat=True)
return Item.objects.filter(id__in=ids, sites=current_site).exclude(id=item.id).order_by('-publish_date')[:3]
关于python - django taggit similar_objects 查询非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29358597/
我正在尝试选择 3 个最近发布的项目,其中任何标签都与当前项目相似(以及其他一些过滤器)找不到有效的方法,数据库中有很多“项目”。 from taggit_autosuggest.managers i
我是一名优秀的程序员,十分优秀!