[Answered ]-Django – a model field which gets the result of model method

1πŸ‘

βœ…

If you would like to add a calculated field like all_members as a part of your model, then you will have to override the save function:

class Home(models.Model):
    ...
    all_members = models.IntegerField()

    def save(self):
        all_members = self.all_people()
        super(Home, self).save()

Now you can filter by all_members. It would be better to use the @property decorator for all_members, in this case.

Another approach would be to use Django’s extra method as mentioned in a different stackoverflow answer

πŸ‘€arocks

1πŸ‘

You still need to define all_members as a model field (not as an integer), and then populate it with the desired value when you save() the instance.

class Home(models.Model):
  ...
  number_female = models.IntegerField()
  number_male = models.IntegerField()
  all_members = models.IntegerField()


  def save(self):
     self.all_members = self.number_female + self.number_male
     super(Home, self).save()
πŸ‘€desired login

0πŸ‘

I think Django Managers can be a solution here. Example:

Custom Manager:

class CustomFilter(models.Manager):
      def all_people(self):
           return self.number_female + self.number_male

Model:

 class Home(models.Model):
     ....
     objects= CustomFilter()

Views:

allpeople= Home.objects.all_people(Home.objects.all())
πŸ‘€ruddra

Leave a comment