开发者

How to test Empty string from database in django?

开发者 https://www.devze.com 2022-12-16 15:05 出处:网络
I\'m having a hard time trying to test weather a record in the database exists for a perticular ID 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:
     tex开发者_JAVA技巧t="No Record"

I need to do something like this.


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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消