2011-02-06 85 views
4

在我的模型,我有:Django的ManyToManyField

class Poll(models.Model): 
    topic = models.CharField(max_length=200) 
    tags = models.ManyToManyField(Tag) 

我試圖創建民意調查對象和存儲標籤,像這樣:

Tags = [] 
for splitTag in splitTags: 
    tag = Tag(name = splitTag.lower()) 
    tag.save() 
    Tags.append(tag) 

如何設置Tags陣列並將其分配到tags

我曾嘗試:

poll = Poll(topic=topic, tags = Tags) 
    poll.save() 

回答

12

那麼,它應該更是這樣的:

models.py 

class Tag(models.Model): 
    name = models.CharField(max_length=200) 

class Poll(models.Model): 
    topic = models.CharField(max_length=200) 
    tags = models.ManyToManyField(Tag) 

in views.py: 

poll = Poll(topic="My topic") 
poll.save() 
for splitTag in splitTags: 
    tag = Tag(name = splitTag.lower()) 
    tag.save() 
    poll.tags.add(tag) 
poll.save() 
3

我看到你正在試圖建立自己的標籤系統,但我認爲它可能如果你看一下已經存在的一個,可以幫助你。

http://code.google.com/p/django-tagging/

我用我的應用程序,它有一個真棒API來啓動。