Login

OrderField

Author:
zenx
Posted:
January 9, 2010
Language:
Python
Version:
1.1
Tags:
models fields field order orderfield integerfield
Score:
1 (after 1 ratings)

OrderField for models from http://ianonpython.blogspot.com/2008/08/orderfield-for-django-models.html and updated to use a django aggregation function. This field sets a default value as an auto-increment of the maximum value of the field +1.

 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. decorator to add GUID Field to Django Models by trubliphone 2 years, 3 months ago
  2. SerializedObjectField by dominno 5 years, 2 months ago
  3. Custom model field to store dict object in database by rudyryk 5 years, 1 month ago
  4. Model field choices as a namedtuple by whiteinge 4 years, 2 months ago
  5. Field value as plain text which can't be edited by user by szczavv 5 years, 8 months ago

Comments

Please login first before commenting.