Fahim Akhter
Fahim Akhter

Reputation: 1625

How to test Empty string from database in django?

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.

Upvotes: 1

Views: 250

Answers (3)

Antony Hatchkins
Antony Hatchkins

Reputation: 34014

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.

Upvotes: 2

jbochi
jbochi

Reputation: 29654

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

Upvotes: 0

Antony Hatchkins
Antony Hatchkins

Reputation: 34014

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

Upvotes: 1

Related Questions