2015-02-08 43 views
1

我有一個輪詢應用程序與Poll模型中的ManytoMany字段。django的意見 - 獲取ManyToMany字段的值

我想檢索視圖中的選項(ManyToMany)字段的值。

models.py

class Poll(models.Model): 
    question = models.CharField(max_length=250) 
    pub_date = models.DateTimeField() 
    end_date = models.DateTimeField(blank=True, null=True) 
    choice= models.ManyToManyField(Choice) 

def __unicode__(self): 
    return smart_unicode(self.question) 

class Choice(models.Model): 
    name = models.CharField(max_length=50) 
    photo = models.ImageField(upload_to="img") 
    rating = models.CharField(max_length=10) 

def __unicode__(self): 
    return smart_unicode(self.name) 

views.py 有2種選擇,在每個調查,我想每一種選擇分配到2個獨立的變量,但不知道怎麼樣。

def polling(request) 
    try: 
     choices = Poll.objects.all() 
     choice_1 = **assign 1st ManyToMany Field value** 
     choice_2 = **assign 2nd ManyToMany Field value** 

回答

1

這樣的事情,我想像

def polling(request): 
    for poll in Poll.objects.all(): 
     choice_1 = poll.choice.all()[0] 
     choice_2 = poll.choice.all()[1] 

def polling(request): 
    for poll in Poll.objects.all(): 
     for choice in poll.choice.all(): 
      # Do something with choice 

注:如果每個調查對象總是具有正好2個選擇,你還不如用foreignkeys代替

class Poll(models.Model): 
    question = models.CharField(max_length=250) 
    pub_date = models.DateTimeField() 
    end_date = models.DateTimeField(blank=True, null=True) 
    choice_one = models.ForeignField(Choice) 
    choice_two = models.ForeignField(Choice) 

那樣,它將不需要第三張表來跟蹤選擇和民意調查之間的關係,這反過來會更有效率。

最後,你應該看看Django文檔,,在解釋這一切做了偉大的工作:https://docs.djangoproject.com/en/1.7/topics/db/examples/many_to_many/

1

末choice_1和choice_2一個小改動,Dellkan的solution..as將是投票在循環中的最後一項

polldict={} 
def polling(request): 
    for poll in Poll.objects.all(): 
     index=poll.id 
     choicedict={} 
     choicedict['choice_1'] = poll.choice.all()[0] 
     choicedict['choice_2'] = poll.choice.all()[1] 
     polldict[index]=choicedict 

使用此,如果調查條目並不大enough..Later您可以訪問的選擇

polldict[id]['choice_1'] 

不是一個大的東西,而是一個小邏輯來解決各種民意調查和選項。