DRY way to call method if object does not exist, or flag set?
<p>I have a Django database containing Paper objects, and a management command to populate the database. The management command iterates over a list of IDs and scrapes information about each one, and uses this information to populate the database. </p>

<p>This command is run each week, and any new IDs are added to the database. If the object already exists, I don't scrape, which speeds things up hugely:</p>

<pre><code>try:
    paper = Paper.objects.get(id=id)
except Paper.DoesNotExist:
    info = self._scrape_info(id)
    self._create_or_update_item(info, id)
</code></pre>

<p>Now I want to set an <code>UPDATE_ALL</code> flag on the management command to update information about existing Paper objects, as well as just creating new ones. The problem is that it's not very DRY:</p>

<pre><code>try:
    paper = Paper.objects.get(id=id)
    if UPDATE_ALL:
        info = self._scrape_info(id)
        self._create_or_update_item(info, id)
except Paper.DoesNotExist:
    info = self._scrape_info(id)
    self._create_or_update_item(info, id)
</code></pre>

<p>How can I make this DRYer?</p>

<p>Django obviously has the <code>get_or_create</code> method, which I'm using in <code>_create_or_update_item</code>. However, I only want to call <code>self._scrape_info</code>, as well as creating or updating the object. </p>

<p>If you want to do something like</p>

<pre><code>obj, created = Paper.objects.update_or_create(
    name='Paper')
</code></pre>

<p>There is a <code>update_or_create</code> in Django since 1.7. 
Take a look into <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#update-or-create" rel="nofollow">docs</a> if that is suitable for you.</p>

<blockquote>
  <p>A convenience method for updating an object with the given kwargs,
  creating a new one if necessary. The defaults is a dictionary of
  (field, value) pairs used to update the object. The values in defaults
  can be callables.</p>
</blockquote>

python django