trubliphone
trubliphone

Reputation: 4504

Django QuerySet filter ValueError not caught?

I am trying to filter a Django QuerySet. I know that sometimes the filter terms will be invalid. In this case, I want to catch the error. Here is a silly contrived example:

models.py:

from uuid import uuid4
from django.db import models

class MyModel(models.Model):
    class Meta:
        app_label = "my_app"
        abstract = False
    guid = models.UUIDField(default=uuid4, editable=False)


try:
    my_filtered_models = MyModel.objects.filter(guid='invalid_guid')
except ValueError:
    print "you messed up"

Now this should raise a ValueError because 'invalid_guid' is not a valid uuid - it ought to be something like ''9a3c21a5-09f7-4676-9ecf-c1672fa69bc0', obviously). But I never reach the except block.

Any suggestions?

Upvotes: 2

Views: 366

Answers (2)

zaidfazil
zaidfazil

Reputation: 9245

From django documentation, quote

class UUIDField(**options)[source]¶

A field for storing universally unique identifiers. Uses Python’s UUID class. When used on PostgreSQL, this stores in a uuid datatype, otherwise in a char(32).

Also, from python docs, quote

class uuid.UUID(hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None)

Create a UUID from either a string of 32 hexadecimal digits, a string of 16 bytes as the bytes argument, a string of 16 bytes in little-endian order as the bytes_le argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as the fields argument, or a single 128-bit integer as the int argument

To be specific to the point,

UPDATE

Finally, I've got it. Actually, django does raises error.

I'll just illustrate with a simple example,

Just try your code,

my_filtered_models = MyModel.objects.filter(guid='invalid_guid')

This code doesn't raises error, because the try statement consists of assignment of whatever the result of the query you just did to the variable "my_filtered_models". But, if you tried to print or access my_filtered_variable, the ValueError is raised.

Infact,

MyModel.objects.filter(guid='invalid_guid')

This statement raises ValueError. I retract my previous answer by deleting it myself, also my apologies for that faulty reply.

So, your code,

try:
    my_filtered_models = MyModel.objects.filter(guid='invalid_guid')
except ValueError:
    print "you messed up"

doesn't enter the except, because, everytime it runs, the ValueError is assigned to my_filtered_models. Only if the variable is accessed, the error is raised.

Hope you got what you were looking for.

Upvotes: 1

David Mutabazi
David Mutabazi

Reputation: 1

Check your invalid_pk it maybe in the range of the valid_pk. Can you please post futher information about valid_pk

Upvotes: 0

Related Questions