2

我在函数中有一个 ajax 调用

console.log("Executing call on " + link);

$.ajax({
  type : "POST",
  url : link,
  data : {"clientId" : selectedClient, "id" : id},
  dataType : "json",
  success : function(retData) {
    console.log(JSON.parse(retData));
  } 
})

在views.py中调用:

def putClientPeerData(request):
  client = Client.objects.get(client = request.REQUEST["clientId"])
  peer = Client.objects.get(client = request.REQUEST["id"])
  ClientPeers.objects.create(client = client, parentorg = peer.parentorg, eff_date = datetime.now(), exp_date = None).save()
  testPeer = ClientPeers.objects.get(client = client, parentorg = peer.parentorg)

  if testPeer.client == client:
    return HttpResponse(simplejson.dumps({"returnValue" : "success"}))
  else:
    return HttpResponse(simplejson.dumps({"returnValue" : "failure"}))

但是,该save方法执行了两次,导致查询出现MultipleObjectsReturned异常testPeer

4

1 回答 1

3

create调用save,没有必要显式调用它。


文档

create(**kwargs)

一种创建对象并将其全部保存的便捷方法。因此:

p = Person.objects.create(first_name="Bruce", last_name="Springsteen")

和:

p = Person(first_name="Bruce", last_name="Springsteen")
p.save(force_insert=True)

是等价的。

于 2013-07-04T17:33:56.510 回答