gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:51:18 25 4
gpt4 key购买 nike

我有一个投票应用程序,其投票模型中有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com