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>You could incapsulate the parsing process into a helper method:</p>

<pre><code>def scrape_new_object(self, id, force_update=False):
    if not force_update:
        try:
            Paper.objects.get(id=id)
            return
        except Paper.DoesNotExists:
            pass

    info = self._scrape_info(id)
    self._create_or_update_item(info, id)
</code></pre>

<p>and then passing <code>UPDATE_ALL</code> as value to <code>force_update</code></p>

<pre><code>MyCommand.scrape_new_object(id, force_update=UPDATE_ALL)
</code></pre>

python django