我有一个民意测验模型中的ManytoMany Field的轮询应用程序。

我想在视图中检索choice(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**

最佳答案

我想像这样的事情

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


注意:如果每个民意调查对象始终只有两个选择,则最好使用外键

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/

关于python - django View -获取ManyToMany字段的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28398105/

10-10 23:50