python - django View - 获取 ManyToMany 字段的值

标签 python django django-models django-templates django-views

我有一个投票应用程序,其投票模型中有一个 ManytoMany 字段。

我想检索 View 中的 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

注意:如果每个 poll 对象总是有 2 个选择,您不妨使用外键来代替

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/

相关文章:

python - 如何使用 MoviePy 批量处理视频文件夹

Python 不导入 Leap Motion 库

python - pandas 中的嵌套 ifelse 替代方案

python - 如何在 pytest 中运行标记为 skip 的测试

django - Nginx + uWSGI 基本配置

python - 无法使用 PIP 安装库

python - 如何为非主日历插入新事件?使用 python gdata

python - 如何在没有数据库的情况下制作自定义表单 - DJANGO

mysql - 是否可以创建 2 个可能不具有相同值的字段?

django 注册 : what's the up-to date 'canonical' way to extend 'contrib.auth.models.User'