Learning Django
Learning Django

Reputation: 265

How to add data to database and show on admin page with calculation

From Django.db import models

Class multi(models.Model):    
    Varone = models.Integer()
    Vartwo = varone * 2

How to do calculations in this class and show that calculations in the admin page of Django.

I tried to Google couldn't find answers.

Upvotes: 0

Views: 93

Answers (2)

JPG
JPG

Reputation: 88469

First of all, python has defined syntax and you should follow those things.
You could display the var_2 by defining a property as below,

from django.db import models


class Multi(models.Model):
    var_1 = models.IntegerField()

    @property
    def var_2(self):
        return self.var_1 * 2


Then override the admin as (change your admin.py )

from django.contrib import admin


class MultiAdmin(admin.ModelAdmin):
    list_display = ('id', 'var_1', 'var_2')


admin.site.register(Multi, MultiAdmin)


You will get the output as this

Upvotes: 1

Hozayfa El Rifai
Hozayfa El Rifai

Reputation: 1442

you need to override the save method

class Multi(models.Model):
    var_one = models.IntegerField(verbose_name = "first number")
    var_two = models.IntegerField(blank=True, null=True,verbose_name = "second number")

    def save(self, *args, **kwargs):
        self.var_two = self.var_one * 2 
        super(Multi,self).save()

    def __str__(self):
        return "multi method => {0} * 2 = {1}".format(self.var_one, self.var_two)

add this to admin.py

from .models import Multi

admin.site.register(Multi)

Upvotes: 3

Related Questions