【问题标题】:django views - get values of ManyToMany fielddjango 视图 - 获取 ManyToMany 字段的值
【发布时间】:2015-02-08 19:06:15
【问题描述】:

我有一个投票应用程序,在投票模型中有一个多对多字段。

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

【问题讨论】:

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


    【解决方案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
    

    注意:如果每个 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/

    【讨论】:

      【解决方案2】:

      Dellkan 解决方案的一个小改动..最后的choice_1 和choice_2 将是循环中 poll 的最后一个条目

      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
      

      如果投票条目不够大,请使用此选项。稍后您可以使用

      访问选项
      polldict[id]['choice_1']
      

      不是什么大事,而是一个小逻辑,可以解决各种民意调查和选项。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-23
        • 2023-01-15
        • 2018-04-26
        • 1970-01-01
        • 1970-01-01
        • 2014-05-27
        • 2017-01-15
        • 1970-01-01
        相关资源
        最近更新 更多