将ForeignKey保存为实例,但无论如何都会抱怨

时间:2016-06-10 15:51:43

标签: django django-models foreign-keys instance

保存具有ForeignKey的对象时,我收到常见错误: '无法分配“(myObject)”:“(我的ForeignKey字段)”必须是实例'。

这个问题得到了明确答复:

django foreign key save

Django - Foreign Key must be an instance

Django ForeignKey Instance vs Raw ID

但解决方案对我不起作用。

models.py

class User(models.Model):
  email = models.EmailField(max_length=100, unique=True)
  password = models.CharField(validators=[MinLengthValidator(8)],max_length=60)
  is_teacher = models.BooleanField(default=0)


class Question(models.Model):
  question_text = models.CharField(max_length=5000)
  pub_date = models.DateTimeField('date asked')
  answered = models.BooleanField(default=False)
  asker = models.IntegerField(default=0)
  def __str__(self):
    return self.question_text
  def was_published_recently(self):
    now = timezone.now()
    return now - datetime.timedelta(days=1) <= self.pub_date <= now;
  def asked_by(self):
    return self.asker

class Answer(models.Model):
  to_question = ForeignKey(Question, null=False)
  pub_date = models.DateTimeField('date answered')
  answer_text = models.CharField(max_length=10000)
  answered_by = ForeignKey(User, null=False)
  def __str__(self):
    return self.answer_text

views.py

@staff_member_required()
def answerQuestion(request):
  if request.method == 'POST':
    form = QuestionAnswerForm(request.POST,label_suffix='',error_class=DivErrorList)
    if form.is_valid():
      answer_text = request.POST['answer_text']
      question_id = request.POST['question_id']
      now = timezone.now()
      try:
        to_question = Question.objects.get(pk=question_id)
        answered_by= User.objects.get(pk=request.user.id)
        Answer.objects.create(answer_text=answer_text, to_question=to_question, pub_date=now, answered_by=answered_by)
        return render(request, 'askWisdom/answerQuestion.html', { 'result':'Thanks for Your Answer' })
      except Question.DoesNotExist:
        return HttpResponse("Question doesn't exist.")
      except User.DoesNotExist:
        return HttpResponse("Answering User doesn't exist.")

    else:
      return render(request, 'askWisdom/answerQuestion.html', {'form': form, 'error_message': form.errors })

实际错误是: '无法分配“用户:sampleUser@gmail.com”:“Answer.answered_by”必须是“用户”实例'。

奇怪的是,我的答案模型有两个ForeignKeys,但在做的时候

Answer.objects.create(answer_text=answer_text, to_question=to_question, pub_date=now, answered_by=answered_by)

错误在第二个ForeignKey(answers_by = answers_by)上标记,但不是第一个(to_question = to_question),假设它们按顺序处理。

好的,所以更改它以强制在数据库级别保存数字ID:

answered_by_id= User.objects.get(pk=request.user.id).id
Answer.objects.create(answer_text=answer_text, to_question=to_question, pub_date=now, answered_by_id=answered_by_id)

我收到错误: 'column answer.id不存在'

在这种情况下,Postgres数据库中有一个名为answers_by_id的实际列,所以我不明白为什么它会寻找一个隐藏的,显然是自动生成的'answer.id'列。

但无论如何,我宁愿让默认方法将实例传递给ForeignKey字段。

我有什么明显的东西可以忽略吗?如果它只是一个错字,我会感到尴尬。

1 个答案:

答案 0 :(得分:0)

除非您设置了自定义用户模型,否则request.user将是django.contrib.auth.models.User个实例,与您的User模型不同。你不应该用这样的密码字段创建自己的模型,这是不安全的。