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 [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---