如何在 views.py 中分配 ForeignKey MySQL 项目?
How to assign ForeignKey MySQL item in views.py?
当我保存我的 NoteForm 时,我想保存我的表单和“笔记”字段,然后我想在 NoteTagModel 中为笔记创建一个“标签”。
目前,我创建了一个新标签,但它没有分配给笔记。我知道下面的代码一定是错误的:
notetag.id = new_note_parse.id
如果我改为:
notetag.note = new_note_parse.id
我收到以下错误:
"NoteTagModel.note" must be a "NoteModel" instance.
下面是我的views.py:
def notes(request):
note_form = NoteForm
notetag = NoteTagModel()
note_form=NoteForm(request.POST)
if note_form.is_valid():
new_note = note_form.save(commit=False)
new_note_parse = new_note
new_note.save()
notetag.id = new_note_parse.id
notetag.tag = "Test"
notetag.save()
return HttpResponseRedirect(reverse('notes:notes'))
context = {
'note_form' : note_form,
'notes' : NoteModel.objects.all(),
'notes_tag' : NoteTagModel.objects.all(),
}
return render(request, "notes/notes.html", context)
我的models.py是:
class NoteModel(models.Model):
note = models.CharField(
max_length = 5000
)
def __str__(self):
return f"{self.note}"
class NoteTagModel(models.Model):
note = models.ForeignKey(
NoteModel,
on_delete=models.CASCADE,
related_name="notes",
blank= False,
null = True,
)
tag = models.CharField(
max_length = 5000
)
def __str__(self):
return f"Note: {self.note} | Tag: {self.tag}"
我的 forms.py:
class NoteForm(ModelForm):
class Meta:
model = NoteModel
fields = [
'note',
]
如有任何帮助,我们将不胜感激
更改 views.py 以反映以下内容:
note = NoteModel.objects.get(id=new_note_parse.id)
notetag.note = note
当我保存我的 NoteForm 时,我想保存我的表单和“笔记”字段,然后我想在 NoteTagModel 中为笔记创建一个“标签”。
目前,我创建了一个新标签,但它没有分配给笔记。我知道下面的代码一定是错误的:
notetag.id = new_note_parse.id
如果我改为:
notetag.note = new_note_parse.id
我收到以下错误:
"NoteTagModel.note" must be a "NoteModel" instance.
下面是我的views.py:
def notes(request):
note_form = NoteForm
notetag = NoteTagModel()
note_form=NoteForm(request.POST)
if note_form.is_valid():
new_note = note_form.save(commit=False)
new_note_parse = new_note
new_note.save()
notetag.id = new_note_parse.id
notetag.tag = "Test"
notetag.save()
return HttpResponseRedirect(reverse('notes:notes'))
context = {
'note_form' : note_form,
'notes' : NoteModel.objects.all(),
'notes_tag' : NoteTagModel.objects.all(),
}
return render(request, "notes/notes.html", context)
我的models.py是:
class NoteModel(models.Model):
note = models.CharField(
max_length = 5000
)
def __str__(self):
return f"{self.note}"
class NoteTagModel(models.Model):
note = models.ForeignKey(
NoteModel,
on_delete=models.CASCADE,
related_name="notes",
blank= False,
null = True,
)
tag = models.CharField(
max_length = 5000
)
def __str__(self):
return f"Note: {self.note} | Tag: {self.tag}"
我的 forms.py:
class NoteForm(ModelForm):
class Meta:
model = NoteModel
fields = [
'note',
]
如有任何帮助,我们将不胜感激
更改 views.py 以反映以下内容:
note = NoteModel.objects.get(id=new_note_parse.id)
notetag.note = note