Note that there are some explanatory texts on larger screens.

plurals
  1. POis there shortcut method called insert_or_update in AppEngine (or perhaps in Django)? Why not?
    primarykey
    data
    text
    <p>I repeat this kind of pattern many times: (and I think isn't this common?)</p> <p><strong>Google App Engine</strong></p> <pre><code># Insert if object doesn't exist, Otherwise Update Object obj = get_or_insert('123', title='Hello World') obj.title = 'Hello World' obj.puts() </code></pre> <p><strong>Django</strong></p> <pre><code># Insert if object doesn't exist, Otherwise Update Object obj, created = Model.objects.get_or_create(id='123', defaults={'title':'Hello World'} if not created: obj.title = 'Hello World' obj.save() </code></pre> <p>It would be good <strong>if</strong> I <strong>could</strong> just call <code>insert_or_update</code>. isn't it? e.g:</p> <pre><code># AppEngine obj = insert_or_update('123', title='Hello World') # Django obj = Model.objects.insert_or_update(id='123', defaults={'title': 'Hello World'}) </code></pre> <h1>UPDATE</h1> <p>Back to App Engine <a href="https://developers.google.com/appengine/docs/python/datastore/modelclass#Model_get_or_insert" rel="nofollow noreferrer">documentation</a>, I found the snippet on what this <code>get_or_insert</code> method doing. Something like the following:</p> <pre><code>def txn(key_name, **kwds): entity = Story.get_by_key_name(key_name, parent=kwds.get('parent')) if entity is None: entity = Story(key_name=key_name, **kwds) entity.put() return entity def get_or_insert(key_name, **kwargs): return db.run_in_transaction(txn, key_name, **kwargs) get_or_insert('some key', title="The Three Little Pigs") </code></pre> <p>I was wondering why a <code>insert_or_update</code> method not being created in both app engine and django.</p> <h2>App Engine Workaround</h2> <pre><code>@classmethod def insert_or_update(cls, key_name, parent=None, **kwargs): def _tx(): entity = cls.get_by_key_name(key_name, parent=parent) if entity: for key in kwargs: setattr(entity, key, kwargs[key]) else: entity = cls(key_name=key_name, parent=parent, **kwargs) entity.put() return entity return db.run_in_transaction(_tx) </code></pre> <h2>Django Solution</h2> <p><a href="https://stackoverflow.com/a/20430268/764592">See Below</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload