gpt4 book ai didi

python - Django教程: where does question_id come from?

转载 作者:行者123 更新时间:2023-11-30 22:51:46 27 4
gpt4 key购买 nike

所以我正在尝试学习 django 并遵循本教程:https://docs.djangoproject.com/en/1.10/intro/tutorial01/

按照教程制作民意调查应用程序后,当我回头查看代码时,我只是不明白这个“question_id”来自哪里。创建模型时不会出现。

以下是模型的代码:

from django.db import models
from django.utils import timezone
import datetime
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text= models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text

在 view.py 中:

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.http import Http404
from django.template import loader
from django.urls import reverse
from django.views import generic

from .models import Question
from .models import Choice
from django.utils import timezone

def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

question_id 凭空出现。

  1. 是否在创建模型时,django会自动为每个实例创建一个model_id?

  2. 此外,另一个问题是为什么他们会执行“pk=question_id”并随后使用 pk。这重要吗?

urls.py 中的代码:

from django.shortcuts import render
from django.conf.urls import url

from . import views

app_name = 'polls'

urlpatterns = [
# ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
# ex: /polls/5/
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
# ex: /polls/5/results/
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
  • 此外,当使用像这样的通用 View 时:

    类 DetailView(generic.DetailView):模型=问题template_name = 'polls/detail.html'

  • 我们可以传入参数(如 Question_id)吗?

    最佳答案

    urls.pyurlpatterns 列表中,您有以下路由:

    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote')

    URL 实际上是一个正则表达式,因此一个字符串可以指定一整组 url。
    question_id 是正则表达式的命名部分,它定义了该 url 的参数。

    当调用 View 时,即 views.vote ,从 URL 解析的 question_id 会作为函数参数发送。

    例如,如果客户端访问以下网址:

     /123/vote/

    然后 View 函数将被调用,如下所示:

     vote(request=request, question_id=123)
    1. Is it the case that when creating a model, django will automatically create a model_id for each instance?

    是的。

    1. Also, another question is why they do "pk=question_id" and use pk thereafter. Does it matter?

    这里 pk 代表“主键”。没关系,实际上,不同的名称只是一个范围问题。

    投票 View 的函数参数名称是“question_id”。 get_object_or_404question.choice_set.get 方法内的函数参数名称是“pk”。

    它们只是指向同一对象的不同名称(例如整数123)。

    关于python - Django教程: where does question_id come from?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38906576/

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