Login

OrderField

Author:
zenx
Posted:
January 9, 2010
Language:
Python
Version:
1.1
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.