Django find_or_create helpers

February 27, 2008 | In: development, django, python

OK I’m going to be completely frank. You VERY likely could do this FAR better. But! I looked and have yet to see anything that does this for Django. So, here is my half ass’d attempt at two very helpful methods I picked up from my shady rails past. So by all means call doodoo on my methods and show me your skills because I would love to see someone else’s take on this. Again shouts out to perva.de for being the inspiration for these snippets and thank ifni for Django giving me reason to be excited about a web framework again.

find_or_create

def find_or_create(class_type, params, by='id'):
   if params == None:return None

   try:
      return class_type.objects.get(by+" = "+params[by])
   except class_type.DoesNotExist:
      obj = class_type()
      for column, value in params:
         if hasattr(obj, column):
         _member = getattr(obj,column)
         _member(value)

      obj.save()

      return obj

update_or_create

def update_or_create(class_type, params, by='id'):
   if params == None:return None

   try:
      obj = class_type.objects.get(by+" = "+params[by])
   except class_type.DoesNotExist:
      obj = class_type()

   for column, value in params:
      if hasattr(obj, column):
         _member = getattr(obj,column)
         _member(value)

         obj.save()

         return obj

called like so:

update_or_create(MyModel, request.POST, 'id')
find_or_create(MyModel, request.POST, 'id')
Bookmark and Share
blog comments powered by Disqus

Flickr Pics

13th and washington NYC13th and 9th NYC1st st Jersey CityIMG_2813IMG_2814_2IMG_2816IMG_2815Photo_011908_001Photo_122807_001Photo_121107_001