[Answered ]-Django queries does datatype matter?

2👍

You can use either ints or strings, which you already did in your question. However, if you pass in a value which cannot be coerced to an int – e.g. .get(id='Hello World') – the model will raise an exception in your code.

If you pass an int, your are much less likely to get an error while querying. However, there’s no harm in passing strings if you are sure they will coerce to ints properly (for example using a regex to validate the string).

Both will work properly because the model field automatically converts the passed value. For example, IntegerField converts the passed value it needs by calling int():

 class IntegerField(Field):

     def get_prep_value(self, value):
         value = super(IntegerField, self).get_prep_value(value)
         if value is None:
             return None
         return int(value)

     def to_python(self, value):
         ...
         try:
             return int(value)
         except (TypeError, ValueError):
             raise ...

This also means that .get(int_field=1.0) will work – the float gets converted to an int!

Unfortunately most of these behavior aren’t documented- you will need to look into the source directly. However, most fields in Django will take either a string or the type of the field itself.

Leave a comment