Jason
Jason

Reputation: 11363

Django model saving twice.. why?

I have an ajax call within a function

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));
  } 
})

that calls in 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"}))

However, the save method executes twice, which results in a MultipleObjectsReturned exception on the testPeer query.

Upvotes: 2

Views: 2005

Answers (1)

Pavel Anossov
Pavel Anossov

Reputation: 62868

create calls save, there's no need to call it explicitly.


Documentation:

create(**kwargs)

A convenience method for creating an object and saving it all in one step. Thus:

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

and:

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

are equivalent.

Upvotes: 3

Related Questions