0

I am using flask-sqlalchemy and have a model representing a fish, which has a birthday as a Date object. Associated with the Fish class is a method which returns the number of months the fish has been alive, is there a way to filter based on what is returned from that custom method?

Here is my code

#the model
class Fish(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    ...
    birthday = db.Column(db.Date)

    #the method for returning number of months
    def getMonths(self):
        if self.status == "Dead":
            return
        if self.birthday == None:
            return

        today = datetime.today().date()
        birthday =  self.birthday
        age_difference = relativedelta.relativedelta(today,birthday)

        return age_difference.months

Here is what I have tried so far

#number or months to filter by
cutoff = 6

#the query
result = Fish.query.filter(Fish.getMonths() >= cutoff).all()

but this is returning a type error, because there is no self passed to the method

TypeError: getMonths() missing 1 required positional argument: 'self'

Any help on how to do this would be greatly appreciated and let me know if you need any more information!

MarcusWilliams
  • 414
  • 2
  • 11
  • 1
    I tried that, and whilst I don't get the error anymore my query is now just returning None no matter what values I pass as the cutoff. There is a chance this may be a problem somewhere else in my code, so I'll have a look at what the cause may be – MarcusWilliams Jul 21 '22 at 10:14
  • 1
    Passing Fish directly does not work, because self is now passed as the class Fish and not each instance of Fish which is what I need. So by passing Fish, the self.birthday returns the attribute for the class which is of type `````` (it prints as just 'Fish.Brithday') rather than returning the birthday as a Date for each instance which is what I'll need for it to work – MarcusWilliams Jul 21 '22 at 10:21
  • 1
    You should use `hybrid_property`, see similar example: https://stackoverflow.com/questions/72877954/sqlalchemy-delete-criteria-where-clause-in-which-one-column-is-to-be-compared/72880015#72880015. – jorzel Jul 21 '22 at 11:20

0 Answers0