我在添加pair时得到此错误。
不能赋值"'1'; "Pair.exchange"必须是"exchange"。实例。
models.py:
class Exchange(models.Model):
name = models.CharField(max_length=25)
def __str__(self) -> str:
return f'{self.name}'
class Pair(models.Model):
symbol = models.CharField(max_length=20)
ask = models.FloatField()
bid = models.FloatField()
exchange = models.ForeignKey(Exchange, on_delete=models.PROTECT)
created = models.DateTimeField()
def __str__(self) -> str:
return f'ID: {self.id} Symbol: {self.symbol} Ask: {self.ask} Bid: {self.bid} Exchange: {self.exchange}'
views.py:
def show_pair(request):
pairs = Pair.objects.all()
br = [str(pair) + '<br>' for pair in pairs]
return HttpResponse(br)
def add_pair(request, symbol, ask, bid, exchange):
pair = Pair.objects.create(symbol=symbol, ask=ask, bid=bid, exchange=exchange)
return HttpResponsePermanentRedirect('/pair/')
urls . py:
path('pair/add/<symbol>/<ask>/<bid>/<exchange>/', views.add_pair)
我试图通过链接添加对,但我得到这个错误,可能是什么问题?
正如错误所述,您不能只传递"Exchange" id"模型,但必须传递模型的实例。
选项1:获取模型实例并传递给它
def add_pair(request, symbol, ask, bid, exchange):
exchange_obj = Exchange.objects.get(id=exchange)
pair = Pair.objects.create(symbol=symbol, ask=ask, bid=bid, exchange=exchange_obj)
return HttpResponsePermanentRedirect('/pair/')
选项2:当你在模型上创建一个ForeignKey
字段时,django会创建一个名为exchange_id
的数据库列,所以你也可以用它来创建你的&;pair &;
def add_pair(request, symbol, ask, bid, exchange):
pair = Pair.objects.create(symbol=symbol, ask=ask, bid=bid, exchange_id=exchange)
return HttpResponsePermanentRedirect('/pair/')
作为奖励,您可能想要添加一些验证,以确保您收到的交换id实际上是正确的。例如,你可以使用django的get_object_or_404
。
def add_pair(request, symbol, ask, bid, exchange):
exchange_obj = get_object_or_404(Exchange.objects.all(), id=exchange)
pair = Pair.objects.create(symbol=symbol, ask=ask, bid=bid, exchange=exchange_obj)
return HttpResponsePermanentRedirect('/pair/')
正如错误所示,您需要提供一个Exchange
对象,但是直接传递exhange_id
更有效:
from django.shortcuts import redirect
from django.views.decorators.http import require_http_methods
@require_POST
def add_pair(request, symbol, ask, bid, exchange):
pair = Pair.objects.create(
symbol=symbol, ask=ask, bid=bid,exchange_id=exchange_id
)
return redirect('/pair/')
你可能应该不应该使用永久重定向,因为浏览器下次不会触发逻辑,而是直接访问重定向。
注意: GET请求不应该具有副作用,因此构造对象,当用户发出GET请求时,不符合HTTP标准。因此,最好将其转换为POST请求。