Home > Enterprise >  How i can fetch fields from models and calculate some filed and pass them to my template?
How i can fetch fields from models and calculate some filed and pass them to my template?

Time:12-16

my model.py

class Main(models.Model):
    name= ....
    amount      = models.PositiveIntegerField(default=40000)

In my views:

def mainf(request):
    listmain = models.Main.objects.all()
    for data in listmain:
        value   =   data.amount * 5
    calculated_data = data_and_value  

    context = {'main':calculated_data}
    return render(request,'main/main.html',context)

How i can fetch fields from models and calculate some fileds and pass them(calculated_data) to my template?

For example i want to calculate salary base on hours. i want to fetch hours from database and calculate hours*500 and then send hours and salary to my template.

data_and_value can be object or anything. i want get this and send to my template

CodePudding user response:

Either define them as properties on the model, or pass them through the context to the template.

If the value is based purely on fields in one model instance, it's good to define a property. For example,

class Thing( models.Model)
    # Thing has height, width, depth fields
    ...
    @property
    def adjusted_volume(self):
        return (self.height 10) * (self.width 10) * (self.depth 10)

In your template (and indeed in your code) you can now refer to {{ thing.adjusted_volume }}, assuming thing was included in the context, either explicitly, or by a class-based-view's context_object_name="thing"

Your question shows an example of passing the result of a computation that's not restricted to a single object instance to the template where you can refer to it as {{ main}} (But the code is incorrect, value gets repeatedly calculated and then thrown away in a loop, and data_and_value is not defined).

  • Related