通过链接添加Pair时触发Django外键赋值错误,如何解决?
问题分析与解决方案
错误核心原因
Cannot assign "'1'": "Pair.exchange" must be a "Exchange" instance.
你从URL传递的exchange是字符串类型的ID(比如'1'),但Pair模型的exchange字段是ForeignKey,它要求接收Exchange模型的实例对象,而非字符串或数字ID的原始值,直接传字符串ID就会触发这个错误。
修复方案一:直接用exchange_id赋值(推荐)
Django会为ForeignKey字段自动生成对应的xxx_id字段,你可以直接把转成整数后的ID赋值给exchange_id,无需先查询实例:
修改views.py中的add_pair函数:
from datetime import datetime def add_pair(request, symbol, ask, bid, exchange): # 转换参数类型,处理格式错误情况 try: ask_float = float(ask) bid_float = float(bid) exchange_id = int(exchange) except ValueError: return HttpResponse("参数格式错误", status=400) # 创建交易对,注意给created字段赋值 pair = Pair.objects.create( symbol=symbol, ask=ask_float, bid=bid_float, exchange_id=exchange_id, # 使用exchange_id替代exchange created=datetime.now() ) return HttpResponsePermanentRedirect('/pair/')
修复方案二:先获取Exchange实例再赋值
如果需要验证交易所是否存在,可以先通过ID查询实例,再传入:
from datetime import datetime from django.http import HttpResponseNotFound def add_pair(request, symbol, ask, bid, exchange): try: ask_float = float(ask) bid_float = float(bid) exchange_id = int(exchange) # 查询对应交易所实例,不存在则返回404 exchange_instance = Exchange.objects.get(id=exchange_id) except ValueError: return HttpResponse("参数格式错误", status=400) except Exchange.DoesNotExist: return HttpResponseNotFound("对应的交易所不存在") pair = Pair.objects.create( symbol=symbol, ask=ask_float, bid=bid_float, exchange=exchange_instance, # 传入Exchange实例 created=datetime.now() ) return HttpResponsePermanentRedirect('/pair/')
额外优化建议
- URL参数类型约束:在
urls.py中指定参数类型,让Django自动转换类型,减少手动处理:
path('pair/add/<str:symbol>/<float:ask>/<float:bid>/<int:exchange>/', views.add_pair)
- 自动填充created字段:修改
models.py中的created字段,设置自动填充当前时间,无需手动赋值:
created = models.DateTimeField(auto_now_add=True)
内容的提问来源于stack exchange,提问作者Xena
相关产品推荐
相关产品推荐

