I think you are looking for get() facilityList = Facility.objects.get(name = facilityName)
http://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups Dougal --- Dougal Matthews - @d0ugal http://www.dougalmatthews.com/ 2009/3/30 famousactress <famousactr...@gmail.com>: > > Hello folks. I'm new to python, new to Django, but very old to ORMs > (via Java's Hibernate, mostly)... > > I naively assumed that QuerySet.filter() would return me None, if > there were no results. Instead it returns an empty list. That's not > terrible, but for some things, it can make code more cumbersome. > Consider the following: > > def ensureFacilityExists(facilityName): > > facilityList = Facility.objects.filter(name = facilityName) > > if len(facilityList) == 1: > return facilityList[0] > elif len(facilityList == 0: > facility = Facility(name = facilityName) > facility.save() > return facility > else: > raise Exception("More than one facility with that name!") > > > This is a bit clunky for this case. I looked for a method on QuerySet > that would clean this up, but didn't find one. I may have missed > something. Here's what I did to clean my case up though: > > def ensureFacilityExists(facilityName): > > facility = Facility.objects.filter(name = facilityName).only() > > if facility == None: > facility = Facility(name = facilityName) > facility.save() > > return facility > > > ... In order to do this, I added the only() method to QuerySet: > > def queryset_only(self): > i = len(self) > if i == 0: > return None > elif i > 1: > raise Exception("More than one element in this querySet!!") > else: > return self[0] > > import new > from django.db.models.query import QuerySet > QuerySet.only = new.instancemethod(queryset_only,None,QuerySet) > > > My question is: > > Is there another facility for doing this already built into Django's > ORM? If not, is this a change that seems valuable to anyone else? > > Thanks, > Phill > > > > --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---