![](/img/trans.png)
[英]In django-taggit, how to get tags for objects that are associated with a specific user?
[英]Django-Taggit get random tags skipping those not assigned to a Post
我想在用戶點擊搜索欄時向用戶提供隨機標簽的建議。 到目前為止,我的代碼返回了我想要的內容但是它還返回了未分配給任何Post IE的標簽:當我刪除帖子或刪除其標簽時,這些標簽仍然出現在建議中。
# 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
如果您只想分配給帖子的標簽,則必須在帖子中查詢其標簽,然后選擇以下五個:
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.