On Mon, Mar 30, 2009 at 5:20 PM, famousactress <[email protected]>wrote:
>
> 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.
I think you missed get_or_create:
http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create-kwargs
Karen
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---