OrderField

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.db.models import fields
from django.db.models import Avg, Max

class OrderField(fields.IntegerField):
    """Ignores the incoming value and instead gets the maximum plus one of the field."""
    def pre_save(self, model_instance, value):
        # if the model is new and not an update
        if model_instance.pk is None:
            records = model_instance.__class__.objects.aggregate(Max(self.name))
            if records:
                # get the maximum attribute from the first record and add 1 to it
                value = records['%s__max' % self.name]  + 1
            else:
                value = 1
        # otherwise the model is updating, pass the attribute value through
        else:
            value = getattr(model_instance, self.attname)
        return value

    
    # prevent the field from being displayed in the admin interface
    def formfield(self, **kwargs):
        return None
    

More like this

  1. BigIntegerField and BigAutoField by fnl 4 years, 5 months ago
  2. Javascript Chain Select Widget by ogo 4 years, 11 months ago
  3. MultiSelectField with comma separated values (Field + FormField) by quinode 1 year ago
  4. PositionField by jpwatts 4 years, 10 months ago
  5. Database migration and dump/load script by akaihola 6 years, 1 month ago

Comments

(Forgotten your password?)