python - DRY way to call method if object does not exist, or flag set? -


i have django database containing paper objects, , management command populate database. management command iterates on list of ids , scrapes information each one, , uses information populate database.

this command run each week, , new ids added database. if object exists, don't scrape, speeds things hugely:

try:     paper = paper.objects.get(id=id) except paper.doesnotexist:     info = self._scrape_info(id)     self._create_or_update_item(info, id) 

now want set update_all flag on management command update information existing paper objects, creating new ones. problem it's not dry:

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) 

how can make dryer?

django has get_or_create method, i'm using in _create_or_update_item. however, want call self._scrape_info, creating or updating object.

if want like

obj, created = paper.objects.update_or_create(     name='paper') 

there update_or_create in django since 1.7. take docs if suitable you.

a convenience method updating object given kwargs, creating new 1 if necessary. defaults dictionary of (field, value) pairs used update object. values in defaults can callables.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -