> Is there a better way to check if there are any hits on a query than > using query.count()>0 ? > > I find myself doing something like this a lot: > modelList = MyModel.objects.filter(someMember=m) > if modelList.count() > 0: > return modelList[0]
This sounds an awful lot like the .get() method of your objects[1]: try: return MyModel.objects.get(someMember=m) except (MyModel.ObjectDoesNotExist, AssertionError): do_something_else() There's even a helper function[2] which can make this cleaner: from django.shortcuts import get_object_or_404 get_object_or_404(MyModel, someMember=m) assuming a 404 is what you want. But you can look at the source as it's just python. In terms of saving a query, you can use the "it's better to ask forgiveness than permission" instead of "look before you leap". The .get() method simply tries to request the objects[0] and if it fails, an exception is raised...no need for the superfluous count() call/query to "look before you leap". That means your original code can just be written as modelList = MyModel.objects.filter(someMember=m) try: return modelList[0] except IndexError: do_something_else() -tim [1] http://www.djangoproject.com/documentation/db-api/#get-kwargs [2] http://www.djangoproject.com/documentation/shortcuts/#get-object-or-404 --~--~---------~--~----~------------~-------~--~----~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---