Pedro Mariz
Pedro Mariz

Reputation: 161

django-admin sum multiple columns

I have a model with several fields. And I wanted to add another field in django-admin (list_display), where it is the sum of all fields.

Model's

class Model1(models.Model):
    field1 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8)
    field2 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8)
    field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8)
    field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8)
    field4 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8)


    def __str__(self):
        return str(self.id)

Model's Admin

class Model1Admin(admin.ModelAdmin):
    model = Model1

    list_display = ('field1','field2',<!--Sum of (field1,field2,field3,field4,field5-->)

admin.site.register(Modell,Model1Admin)

i am using the last version of django.

Upvotes: 0

Views: 306

Answers (2)

Germano
Germano

Reputation: 636

if you want you can do something like that:

1- Create a property in your model:

class Model1(models.Model):
    field1 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8)
    field2 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8)
    field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8)
    field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8)
    field4 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8)


    def __str__(self):
        return str(self.id)

    @property
    def final_sum(self):
        return self.field1 + self.field2 + self.field3 + self.field4 + self.field5

2- Then use it in your admin.py

class Model1Admin(admin.ModelAdmin):
    model = Model1

    list_display = ('final_sum', 'field1','field2', )

admin.site.register(Modell,Model1Admin)

Upvotes: 1

iklinac
iklinac

Reputation: 15738

From Django admin docs regarding list_display

There are four types of values that can be used in list_display:

....

A callable that accepts one argument, the model instance. For example:

def upper_case_name(obj):
    return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name'

class PersonAdmin(admin.ModelAdmin):
    list_display = (upper_case_name,)

so in your case you can create method something like following

def field_sum(obj):
    attribute_list = [ 'field1','field2',...]
    return sum(getattr(obj, attribute) or 0 for attribute in attribute_list)

field_sum.short_description = 'Field sum'

Upvotes: 1

Related Questions