tags:

views:

24

answers:

3

Hi,

I'm having a hard time trying to test weather a record in the database exists for a perticular ID in django.

something = User.objects.get(id=myID)
if something is None:
     text="No Record"

I need to do something like this.

A: 
if not User.objects.filter(id=myID):
    text = "No Record"
Antony Hatchkins
A: 

You can either use Antony Hatchkins' solution or:

try:
    something = User.objects.get(id=myID)
except User.DoesNotExist:
     text="No Record"

EDIT: There is a shortcut that is very handy:

from django.shortcuts import get_object_or_404

def my_view(request):
    my_object = get_object_or_404(MyModel, pk=1)

This example is equivalent to:

from django.http import Http404

def my_view(request):
    try:
        my_object = MyModel.objects.get(pk=1)
    except MyModel.DoesNotExist:
        raise Http404
jbochi
+2  A: 

Since rev 11646 (3 months ago) django has a special function for that (see ticket 11402):

if not User.objects.filter(id=myID).exists():
    text = "No Record"

That is more efficient since it generates EXISTS sql statement instead of populating the python object.

Antony Hatchkins
+1 This is much better than my own answer
jbochi
Thanks for appreciation
Antony Hatchkins
I'm using an older version of django, exist is not allowed sadly.
Fahim Akhter