1

I am trying to do a many to many serialize and can not find a way to pass an object in order to get a count for how many of each award a certain post received. The code below gives the error: TypeError: serialize_awards() missing 1 required positional argument: 'post'

For some reason it will not let me pass an instance of self into the function. I am not sure why as it is required to do the count. Any help would be greatly appreciated.

class Post(SearchableMixin, db.Model):
    id=db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(300))

    @property
    def serialize(self):
        #return {c.name: getattr(self, c.name) for c in self.__table__.columns}
        #return { c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs }
        return {
        'id'    : self.id,
        'title' : self.title,
        #'awards'  : self.serialize_awards
        'awards'  : self.serialize_awards(post=self)
        }

    @property
    def serialize_awards(self, post):
        return [award.serialize for award in self.award_types()]

    def award_types(self):
        return Award_Type.query.order_by(Award_Type.cost.desc()).all()

class Award_Type(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)

    @property
    def serialize(self):
        return {
        'name' : self.name,
        'count': self.count(post)
        }

    def count(self, post):
        return Award.query.filter_by(award_id=self.id, post_id=post.id).count()
rockets4all
  • 684
  • 3
  • 8
  • 32

1 Answers1

1

Thanks for the help from Ian Wilson. I got rid of the @property and made it a direct query.

I converted this:

    @property
    def serialize_awards(self, post):
        return [award.serialize for award in self.award_types()]

into this:

    def serialize_awards(self, post):
        award_dict={}
        for award in self.award_types():
            if award.count_award(post)>0:
                award_dict[award.name]=award.count_award(post)
        return award_dict
rockets4all
  • 684
  • 3
  • 8
  • 32