Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading