簡體   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