2011-06-15 52 views
1

我在一個free-time project過濾器,我有這個模型:Django的標記 - 由標籤

class Post(models.Model): 
    title = models.CharField(max_length=255) 
    <..> 
    tags = TagAutocompleteField() 

TagAutocompleteField()是相同TagField()django-tagging女巫簡單CharField所以print post.tags會給'one two three'而不是['one', 'two', 'three',]

此外,我有一個觀點:

def tagged(request, tag_id): 
    tag = get_object_or_404(Tag, pk=tag_id) 
    post_list = Post.objects.all() \ 
       .filter(tags__split__in=tag) \               
       .filter(is_published=True) \ 
       .order_by('-time_publish') 
    return render_to_response('plugins/persona/list.html', { 
           'post_list': post_list, 
           }) 

的問題是,我不能過濾所有具有特定標籤,因爲標籤是charField我試着使用split()但過濾器不允許它的職位。

人建議使用此功能來獲取標記列表:

def get_tags(self):                     
    return Tag.objects.get_for_object(self) 

但我還是不能把它在過濾器中也可以使用。

我應該如何獲得所有具有相同標籤的帖子?標記的常用方式是通過標記獲取對象,但如果標記僅由少數應用程序使用,則可能不僅僅是發佈帖子。

回答

2

嘗試使用regex

.filter(tags__iregex=r'\b%s\b' % tag) 
+0

可能幾乎所有的世界問題可以用正則表達式解決...它的工作原理謝謝:) – JackLeo 2011-06-16 07:26:27

+0

應該有注意,MySQL正則表達式在Python不同。 – JackLeo 2011-08-29 09:34:24