I have an object with a DecimalField value of 5.60. I'm making a query:
Mdl.objects.get(speed__iexact="5.60")
This will return the correct result. But this will not:
Mdl.objects.get(speed__iexact="5.6")
Is there a way to automatically reconcile this inconsistency? The filter value is user provided, so I want to be sure that a user typing 5.6 can find the object.
iexact does an case-insensitive equality check, which is normally used for strings. For decimals with two decimal places, the Django database backend will probably store "5.60" as string for a DecimalField, so iexact-comparison with that will work because the strings are equal. But as you want to compare numbers, not strings, you should just use the normal equality operator.
from decimal import Decimal
Mdl.objects.get(speed=Decimal("5.6"))
Don't use strings, instead use the Python-builtin Decimal type. When retrieving model instances with Django, you will get instances of that type anyway, so you should also assign this type in order to be consistent.
Related
How can we setup a field in a model to accept more than on value?
We simply can make relation fields using foreign key or many to many but in case of simple int or float or any simple variable type , how can we achieve multi value field?
If it is only about the database field, you could simply serialize your values into a string, e.g. values 1, 2, 3 become "1,2,3" in the field. Simply overwrite the getter and setter for that field (using #property), to serialize and unserialize the values each time the field is accessed.
Another approach is to use a JSONField (doc). This has wider support (for example searchability via querysets, at least using PostGreSQL. Also several 3rd party JSON form fields. You'd need to validate that the JSON supplied was a list of integers).
Such a simple question, but can't seem to find anything in the documentation about it.
For example, can integers be negative?
There is none. Any integer is valid. Negative is definitely fine. But the IntegerField is not limited by default. #16747 closed Bug (wontfix) IntegerField could validate too large numbers to work with PostgreSQL and MySQL be default was a request to fix this, but it was denied.
Keep in mind that an IntegerField is not necessarily connected to a particular database field. It usually is, in which case the recommendation is to add max_value and min_value to match your database field requirements.
If you're talking about models.IntegerField then there is indeed a range for that and it is mentioned in the documentation.
An integer. Values from -2147483648 to 2147483647 are safe in all
databases supported by Django.
It uses MinValueValidator and MaxValueValidator to validate the input
based on the values that the default database supports.
If you're talking about forms.IntegerField, then the only way to validate it is to pass a parameter of max_value and min_value for that.
Validates that the given value is an integer. Uses MaxValueValidator
and MinValueValidator if max_value and min_value are provided.
I need to do some operations on one collection and at the end store the result in another collection. Will be doing this via aggregation. Platform is node, mongoose, mongodb.
One of the required operations which I can't figure out is urlEncoding a particular field. The field can be constrained to only contain alphabets, numbers and spaces, so basically what I need to do is convert spaces to %20
Note that I need to do this while using node. I am pretty new in node, mongoose, mongodb, etc, so I'm not sure If I can run custom javascript code from node into mongoose or if that will be a good idea.
You can use encodeURIComponent() to url encode a string in javascript.
You could do this on all field values before storing them, but only if you're sure you'll never need the original value (the converse method, decodeuricomponent() may not always honor things such as case).
Alternatively, you could store the value 'as is', and use encodeURIComponent() when retrieving the value.
In my models I need to store a mobile number in the following format 447182716281. What field should I use? Does Django have anything to support this?
example
mobile = models.IntegerField(max_length=12)
Phone numbers must be CharFields. Integer field will not preserve leading 0, +, and spacing.
I think is a interesting question since it really depends on the problem modeling, CharField works fine, but have a look at this:
ORM tricks
There is a regex field in form validation. In model use just CharField.
On using models.IntegerField(default=0)
for larger number it gives error
Ensure this value is less than or equal to 2147483647.
So better way to use would be.
BigIntegerField
A 64-bit integer, much like an IntegerField except that it is guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807. The default form widget for this field is a TextInput.
with PostgreSQL IntegerField is not working properly so it's better to use CharField with Django.
Number=models.CharField(max_length=12)
Is there a difference between filter and exclude in django? If I have
self.get_query_set().filter(modelField=x)
and I want to add another criteria, is there a meaningful difference between to following two lines of code?
self.get_query_set().filter(user__isnull=False, modelField=x)
self.get_query_set().filter(modelField=x).exclude(user__isnull=True)
is one considered better practice or are they the same in both function and performance?
Both are lazily evaluated, so I would expect them to perform equivalently. The SQL is likely different, but with no real distinction.
It depends what you want to achieve. With boolean values it is easy to switch between .exclude() and .filter() but what about e.g. if you want to get all articles except those from March? You can write the query as
Posts.objects.exclude(date__month=3)
With .filter() it would be (but I not sure whether this actually works):
Posts.objects.filter(date__month__in=[1,2,4,5,6,7,8,9,10,11,12])
or you would have to use a Q object.
As the function name already suggest, .exclude() is used to exclude datasets from the resultset. For boolean values you can easily invert this and use .filter() instead, but for other values this can be more tricky.
In general exclude is opposite of filter. In this case both examples works the same.
Here:
self.get_query_set().filter(user__isnull=False, modelField=x)
You select entries that field user is not null and modelField has value x
In this case:
self.get_query_set().filter(modelField=x).exclude(user__isnull=True)
First you select entries that modelField has value x(both user in null and user is not null), then you exclude entries that have field user null.
I think that in this case it would be better use first option, it looks more cleaner. But both work the same.