类型错误:字段'id'需要一个数字,但得到 ['database'];多对多字段



Question模型Question.tagsManyToMany字段中添加一组对象时遇到问题。在包含question.tags.add(tags)的行上传递Tag实例集时,会引发以下错误:

  • TypeError: Field 'id' expected a number but got ['database']

为什么将模型实例列表添加到ManyToMany字段会导致此错误?

class AskQuestionPage(Page):
template_name = "posts/ask.html"
extra_context = {
'title': "Ask a public question"
}
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = QuestionForm
return context

def post(self, request):
context = self.get_context_data()
form = context['form'](request.POST)
if form.is_valid():
profile = Profile.objects.get(user=request.user)
form.cleaned_data['profile'] = profile
tags = form.cleaned_data.pop("tags")
question_tags = []
for name in tags:
try:
tag = Tag.objects.get(name=name)
except Tag.DoesNotExist:
tag = Tag.objects.create(name=name)
finally:
question_tags.append(tag)
question = form.save()
question.tags.add(question_tags)
return SeeOtherHTTPRedirect(
reverse("posts:question", kwargs={"id": question.id})
)
return self.render_to_response(context)
class QuestionForm(ModelForm):
title = CharField(
min_length=20, max_length=80,
widget=TextInput({"class": "question_input_shade fill_block_width"}),
error_messages={"max_length": "The title of your question is too long"},
help_text="Concisely describe the issue"
)
body = CharField(
widget=Textarea(attrs={"class": "question_input_shade fill_block_width adjust_box"}),
min_length=50,
help_text="Clarify your question with as much detail as possible",
error_messages={
'required': "Elaborate on your question",
'min_length': "Add more info to your question"
}
)
tags = TagField(
widget=MultiTagWidget(
attrs={
"min_length": 1, "max_length": 25,
"class": "question_input_shade inline_tag_input"
}
), require_all_fields=False,
help_text="Add up to 4 tags for your question"
)
class Question(Post):
title = CharField(
max_length=80, unique_for_date="date",
help_text="Concisely state the problem you're having",
error_messages={
"max_length": "The title of your question is too long"
}
)
tags = ManyToManyField(
'Tag', related_name="questions", related_query_name="question"
)
views = IntegerField(default=0)
objects = Manager()
postings = QuestionSearchManager()

class Meta(Post.Meta):
db_table = "question"
ordering = ["-score" , "-date"]
constraints = [UniqueConstraint(fields=[
'title', 'date', 'profile'
], name="duplicated_post_by_date")]
class Tag(Model):
name = CharField(unique=True, max_length=25)

class Meta:
managed = True
db_table = "tag"

def __str__(self):
return f"{self.name}"

您需要解压缩这些值,因为它有多个关联的id。

question.tags.add(*question_tags) 

最新更新