gpt4 book ai didi

Python/Django - 为对象提供刚刚创建的外键时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:54:51 25 4
gpt4 key购买 nike

我正在扩展基本的 django Poll 站点教程,并且我制作了一个允许用户添加自己的民意调查的 View 。添加投票有效,添加选择则无效。显然这是因为民意调查尚未“存在”,并且无法使用 p.id。但是,当在底部重定向浏览器时,p.id 会起作用。有什么想法吗?

def save(request):
p = Poll(question=request.POST['question'], pub_date=timezone.now())
p.save()
c1 = Choice(poll=p.id, choice_text=request.POST['c1'], votes=0)
c2 = Choice(poll=p.id, choice_text=request.POST['c2'], votes=0)
c3 = Choice(poll=p.id, choice_text=request.POST['c3'], votes=0)
c4 = Choice(poll=p.id, choice_text=request.POST['c4'], votes=0)
c1.save()
c2.save()
c3.save()
c4.save()
return HttpResponseRedirect(reverse('detail', args=(p.id,)))

最佳答案

没关系,我已经明白了。选择不需要 id,而是需要对象。通过更改修复:

c1 = Choice(poll=p.id, choice_text=request.POST['c1'], votes=0)

c1 = Choice(poll=p, choice_text=request.POST['c1'], votes=0)

关于Python/Django - 为对象提供刚刚创建的外键时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17505091/

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