2015-02-08 66 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'] 

不是一个大的东西,而是一个小逻辑来解决各种民意调查和选项。