Django报错:Field 'id'期望数字却获'autobiography'的技术问询
问题原因与解决方案
错误原因
你在test视图中执行Books.objects.filter(collection="autobiography")时出现报错,因为Books模型的collection字段是外键,默认会把传入的参数当作关联模型BookDetails的id(数字类型)处理,但你传入了字符串"autobiography",类型不匹配导致报错。
解决方法
1. 修正筛选查询语句
要按分类名称筛选书籍,需要通过外键关联的BookDetails模型的collections字段查询,使用Django的双下划线(__)跨表查询语法:
def test(request): # 修改filter条件,通过外键关联的字段查询 data = Books.objects.filter(collection__collections="autobiography") template = loader.get_template('test.html') context = {"data": data} return HttpResponse(template.render(context, request))
2. 优化分类创建逻辑(可选但推荐)
当前上传书籍时,每次都会新建一条BookDetails记录,即使相同分类已经存在,这会导致分类数据冗余。可以改用get_or_create方法复用已有分类:
def books(request): if request.method == "POST": form = BookFile(request.POST, request.FILES) files = request.FILES.getlist("book") try: if form.is_valid(): # 复用已有分类,不存在则创建 collection, created = BookDetails.objects.get_or_create( collections=form.cleaned_data['collections'] ) if files: for f in files: names = str(f) name = names.strip(".pdf") Books.objects.create(collection=collection, book_title=name, book=f) return redirect(index) except IntegrityError: messages.error(request, "value exist in database") return redirect(books) else: form = BookFile() return render(request, "books.html", {"form": form})
3. 外键默认值修正(可选)
Books模型中collection外键的default=""设置不合理,外键应关联BookDetails实例,若允许分类为空,可改为:
collection = models.ForeignKey(BookDetails, on_delete=models.CASCADE, null=True, blank=True)
若分类为必填项,则直接去掉default="",确保表单必须选择分类。
内容的提问来源于stack exchange,提问作者Olasubomi
相关产品推荐
相关产品推荐

