Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Django FloatField with maximum and minimum limits?

I'm storing some floating-point data in my Django models, and only a certain range of values are meaningful. Therefore, I'd like to impose these limits at both the model and SQL constraint level.

For example, I'd like to do something like this:

class Foo(Model):    myfloat = FloatField(min=0.0, max=1.0) 

I want to do this at the model level, not the form level. In fact, I might like the form level to have a different range; e.g., use percentages [0,100] at the form level but translate to [0,1] in the model.

Is this possible, and if so, how would I go about doing it?

like image 961
Reid Avatar asked May 10 '12 17:05

Reid


People also ask

What is model float field in Django?

FloatField is a floating-point number represented in Python by a float instance. This field is generally used to store huge floating point numbers in the database. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise. Syntax: field_name = models.FloatField Django Model FloatField Explanation

How to store empty values in a float field in Django?

For example, adding an argument null = True to FloatField will enable it to store empty values for that table in relational database. Here are the field options and attributes that an FloatField can use. If True, Django will store empty values as NULL in the database.

What is the default value of a field in Django?

Default is False. If True, the field is allowed to be blank. Default is False. The name of the database column to use for this field. If this isn’t given, Django will use the field’s name. The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.

What happens if a field is not given a name in Django?

If this isn’t given, Django will use the field’s name. The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.


2 Answers

The answers so far describe how to make forms validate. You can also put validators in the model. Use MinValueValidator and MaxValueValidator.

For example:

from django.core.validators import MaxValueValidator, MinValueValidator  ... weight = models.FloatField(     validators=[MinValueValidator(0.0), MaxValueValidator(1.0)], ) 

EDIT:

However, that does not add a SQL constraint.

You can add SQL constraints as described here as CheckConstraints in Meta.constraints.

Combined example:

from django.core.validators import MaxValueValidator, MinValueValidator from django.db.models import CheckConstraint, Q  class Foo(Model):     myfloat = FloatField(min=0.0, max=1.0,         # for checking in forms         validators=[MinValueValidator(0.0), MaxValueValidator(1.0)],)      class Meta:         constraints = (             # for checking in the DB             CheckConstraint(                 check=Q(myfloat__gte=0.0) & Q(myfloat__lte=1.0),                 name='foo_myfloat_range'),             ) 
like image 87
3 revs, 2 users 97% Avatar answered Sep 29 '22 19:09

3 revs, 2 users 97%


If you need constraint on form level you can pass min_value and max_value to form field:

myfloat = forms.FloatField(min_value=0.0, max_value=1.0) 

But if you need to move it up to model level you have to extend base models.FloatField class

class MinMaxFloat(models.FloatField):     def __init__(self, min_value=None, max_value=None, *args, **kwargs):         self.min_value, self.max_value = min_value, max_value         super(MinMaxFloat, self).__init__(*args, **kwargs)      def formfield(self, **kwargs):         defaults = {'min_value': self.min_value, 'max_value' : self.max_value}         defaults.update(kwargs)         return super(MinMaxFloat, self).formfield(**defaults) 

Then you can use it in models

class Foo(models.Model):     myfloat = MinMaxFloat(min_value=0.0, max_value=1.0) 
like image 40
San4ez Avatar answered Sep 29 '22 20:09

San4ez