【问题标题】:How to set the question that an answer will be associated with?如何设置答案将关联的问题?
【发布时间】:2020-07-15 12:43:03
【问题描述】:

我正在建立一个用于练习的问答网站,我希望每个答案都与作者和问题相关联,我设法将其与用户相关联,但我无法弄清楚问题部分。

代码如下:

models.py:

class Questiont(models.Model):
    question = models.CharField(max_length=200)
    description = models.TextField(null = True , blank=True)
    date_posted =models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User,on_delete=models.CASCADE)

    def __str__(self):
        return self.question

class Answer(models.Model):
    content = models.TextField(null=True,blank=True)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    date_posted = models.DateTimeField(default=timezone.now)

views.py(关联应该发生的地方):

class CreateAnswer(LoginRequiredMixin,CreateView):
    model = Answer
    fields = ['content']
    context_object_name = 'answer'
    success_url = reverse_lazy('Lisk home')


    def form_valid(self, form):
        form.instance.question = ?????????
        form.instance.author = self.request.user
        return super().form_valid(form)

如何指定答案指定的问题(form.instance.question)?假设正在回答的问题的 ID 在回答页面(模板)的 URL 中。

网址是这样的:

http://127.0.0.1:8000/question/22/createanswer/

urls.py(不是root):

politicspost=questioon (sorry if this is messy)

 path('politics_topic/', views.Politics_topic.as_view(template_name='lisk_templates/politics_topic_template.html'),
         name='Politics_topic'),
    path('ask_politics/', views.Questionpolitics.as_view(template_name='lisk_templates/ask_politics_template.html'),
         name='ask_politics'),
    path('politicspost/<int:pk>/',views.Politics_post_details.as_view(template_name='lisk_templates/politics_post_details.html'),
         name='politics_post_details'),
    path('politicspost/<int:pk>/update/',views.Updatepolitics.as_view(template_name='lisk_templates/ask_politics_template.html'),
         name='updatepoliticspost'),
    path('politicspost/<int:pk>/delete/',views.Deletepoliticspost.as_view(template_name='lisk_templates/delete_politics_confirmation.html'),name ='deletepoliticspost'),

    #ANSWER
    path('politicspost/<int:id>/createanswer/',views.CreateAnswer.as_view(template_name='lisk_templates/createanswer.html'),name = 'createanswer'),
    path('answers/',views.Answerslist.as_view(template_name='lisk_templates/politics_post_details.html'),name ='answers')

提前致谢。

【问题讨论】:

  • 能否请您包含您的 urls.py 文件?

标签: python python-3.x django django-models django-views


【解决方案1】:

当您在一个视图/url 路径中处理多个对象时,使用描述性名称总是很方便:使用question_id 而不是id,这样它就不同于answer_id,您稍后可能需要:例如/politics_post/&lt;int:question_id&gt;/answers/&lt;int:answer_id&gt;/change/

这些名称只是标签。它们保存在 CreateView 的 kwargs 属性中。所以/politics_post/42/answers/59/change 将创建: CreateView.kwargs = {'question_id': 42, 'answer_id': 59}。更多信息在the docs

正如@crimsonpython24 所说,您可以从问题的角度执行此操作,但使用 Answer 作为您的模型同样可以。现在,我假设您将 url 更改为有 question_id。您可以像这样更改您的创建视图:

class CreateAnswer(LoginRequiredMixin,CreateView):
    model = Answer
    fields = ['content']
    context_object_name = 'answer'
    success_url = reverse_lazy('Lisk home')
    question_kwarg = 'question_id'


    def form_valid(self, form):
        try:
            question = Question.objects.get(pk=self.kwargs[self.question_kwarg])
        except Question.DoesNotExist:
            form.add_error(None, 'Invalid question')
            return self.form_invalid(form)
        form.instance.question = question
        form.instance.author = self.request.user
        return super().form_valid(form)

【讨论】:

  • 如果我要将 id 重命名为 question_id 和模型问答模型下的 answer_id 字段,是否必须清空数据库?如果不是,我应该为新字段(question_id 和 answer_id)分配什么默认值?
  • 不,和数据库无关。这只是一个标签。我会用更多细节更新答案。
  • 它给了我一个 KeyError 'question_id' @Melvyn
【解决方案2】:

看到您已经在使用基于类的视图,我建议使用内置的UpdateView。这样,您不必进行额外的处理,因为您需要在 URL 中输入问题的主键(答案将成为其中的一部分),Django 将自行获取相应的问题.

尽管对我来说,您的视图名称具有误导性。是的,您正在创建一个答案,但您也在更新父问题对象,我相信这导致您选择 Createview 而不是 Updateview - 第二个会更有利。

基本上,您将添加一个答案,但在问题对象下处理它更方便。

【讨论】:

  • 所以我可以用 Question 模型下的文本字段替换 Answer 模型?
  • 嗯,一个问题有多个答案,所以一个简单的 ForeignKey 就可以解决问题(here 文档)。您不能使用文本字段,因为 Answer 是一个对象。
  • 是否可以为答案设置作者和日期??
  • 对于作者,您可以创建一个Author 模型并将其放在OneToOne field我假设,既然您说“an”,那么只有一个作者,否则你将不得不使用ForeignKey。一个简单的 DateFieldDateTimeField(包括 21:29 但不包括第一个)可以解析为日期,而两者都是 Django 原生的。
猜你喜欢
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 2019-09-02
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多