繁体   English   中英

使用django-taggit获取与父对象关联的所有标签

[英]Getting all the tags associated with the parent object using django-taggit

我有RestaurantReview模型。 Review具有TaggableManager()在使标签适用于评论方面我没有问题。 但我也想知道与Restaurant对象关联的所有标签。

我可以编写自己的函数来遍历餐厅的所有评论,以获得与餐厅相关的所有标签。 但是我正在寻找一种更简单的方法来获取在单个数据库查询中完成该操作的标签。

我认为在单个查询中是不可能的,但是此解决方案将需要五个数据库查询:

# 1 query: Get restaurant
restaurant = Restaurant.objects.get(pk=pk)

# 2 query: Get content type of restaurant model
restaurant_ct = ContentType.objects.get_for_model(restaurant)

# 3 query: Get all reviews ids for a restaurant
reviews_ids = Review.objects.filter(content_type__id=restaurant_ct.id, object_id=restaurant.id).values_list('id', flat=True)

# 4 query: Get content type of review model
review_ct = ContentType.objects.get(app_label='review', model='review')

# 5 query: Get all tags
tags = TaggedItem.objects.filter(object_id__in=reviews_ids, content_type__id=review_ct.id)

但是请注意,在审阅ID上的__in查找可能在TaggedItem上变得昂贵。 但是您想要最少的数据库查询。

您可以通过在单个查询中同时获取餐厅和评论模型的内容类型来减少一个查询,但这不是一种优雅的方式:

ctypes = ContentType.objects.filter(
    app_label__in=['review', 'restaurant'],
    model__in=['review', 'restaurant']
)
assert len(ctypes) is 2
if ctypes[0].model == 'restaurant':
    restaurant_ct = ctypes[0]
    review_ct = ctypes[1]
else:
    review_ct = ctypes[0]
    restaurant_ct = ctypes[1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM