-1

models.py

class Report(models.Model):<br>
    msp = models.IntegerField(blank=True, null=True)
    msp2 = models.IntegerField(blank=True, null=True)
    ago = models.IntegerField(blank=True, null=True)
    total = models.IntegerField(blank=True, null=True)
    date_posted = models.DateTimeField(auto_now=True)

    def __str__(self):
        return 'Report{}'.format(self.id)

    class Meta:
        verbose_name_plural = 'Reports'

views.py

def view(request):<br>
    open_stock = Report.objects.all()
    msp = Report.objects.get(msp)


    context = {'open_stock': open_stock}
    return render(request, 'Strt/view.html', context)
Sociopath
  • 13,068
  • 19
  • 47
  • 75

1 Answers1

1

If i understand your question you are looking to store a computed field in a database, this goes against normalization rules and unless you cannot afford the performance hit for calculating the field at runtime this shouldn't really be done.

If for some reason you need to do it then you would most likely want to override the models save method in models.py and add the total value to the model (self in the save function):

def save(self, *args, **kwargs):
    self.total = msp + msp2
    super(Model, self).save(*args, **kwargs)
Sirwill98
  • 324
  • 1
  • 13
  • Thank you for answering, But if i may explain more in details. This is what im trying to achieve i want to be able to input values in msp and msp2 in the admin panel then sum them up and save the summed results of msp and msp2 in total. – Life with George Jan 18 '21 at 08:24
  • If im not missing something thats what the save function would achieve, when the model is saved it would set its total field to msp+msp2 and then save so the total field would have the value stored, again this is not the best practice though, i would instead make a calculated field in the model so you arent storing calculated data – Sirwill98 Jan 18 '21 at 08:26
  • How do i go about creating a calculated field in the model – Life with George Jan 18 '21 at 08:37
  • https://stackoverflow.com/questions/17682567/how-to-add-a-calculated-field-to-a-django-model this question should help you with that, any questions feel free to ask and i hope i managed to help you out :) – Sirwill98 Jan 18 '21 at 08:40