2017-05-31 47 views
1

我想給我的用戶隨機變量的建議時,他們點擊搜索欄上。到目前爲止,我的代碼返回我想要什麼,但它也返回未分配給任何帖子IE標籤:當我刪除帖子或刪除其標籤這些標籤仍顯示在建議了。Django的Taggit獲得隨機標籤跳過那些沒有分配到郵政

# Get the suggestions (In View) 
suggestions = Tag.objects.all().distinct().order_by('?')[:5] 

# Model 
class Post(models.Model): 
title = models.CharField(max_length=256) 
disclaimer = models.CharField(max_length=256, blank=True) 
BLOGS = 'blogs' 
APPLICATIONS = 'applications' 
GAMES = 'games' 
WEBSITES = 'websites' 
GALLERY = 'gallery' 
PRIMARY_CHOICES = (
    (BLOGS, 'Blogs'), 
    (APPLICATIONS, 'Applications'), 
    (GAMES, 'Games'), 
    (WEBSITES, 'Websites'), 
) 
content_type = models.CharField(max_length=256, choices=PRIMARY_CHOICES, default=BLOGS) 
screenshot = models.CharField(max_length=256, blank=True) 
tags = TaggableManager() 
body = RichTextField() 
date_posted = models.DateTimeField(default=datetime.now) 
date_edited = models.DateTimeField(blank=True, null=True) 
visible = models.BooleanField(default=True) 
nsfw = models.BooleanField() 
allow_comments = models.BooleanField(default=True) 
files = models.ManyToManyField(File, blank=True) 

def __str__(self): 
    if (self.visible == False): 
     return '(Hidden) ' + self.title + ' in ' + self.content_type 
    return self.title + ' in ' + self.content_type 

回答

0

如果你想只分配到職位你要查詢的職位爲自己的標籤,並選擇這五個標籤:

allposts = Post.objects.all() 
five_tags = list(set([tag.slug for post in allposts for tag in post.tags.all()]))[:5] 

(使用set()刪除重複)

編輯

如果你想洗牌的所有標籤挑五前,你可以這樣做:

import random 

allposts = Post.objects.all() 
all_tags_list = list(set([tag.slug for post in allposts for tag in post.tags.all()])) 
random.shuffle(all_tags_list) 
five_tags = all_tags_list[:5] 
+0

第二位做我想要的,但是你知道爲什麼它會返回帶有空格的標記嗎?而不是它爲什麼只返回小寫字母? – Anon

+0

沒關係通過用tag.name替換tag.slug我實現期望的效果。 – Anon