0

I am performing a count() and group_by() operation on a table as follows:

db.session.query(func.count(Tag.name), Tag.name).group_by(Tag.name).limit(limit)

and serialize it using marshmallow:

class TagSchema(ma.ModelSchema):
    class Meta:
        model = Tag
    name = fields.String(validate=validate.Length(min=1))

which gives me result as :

[{"name" : "asdf"},{"name":"qwer"}]

but I don't see the count value, how should I update the schema to get count value in the output.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Jibin Mathew
  • 4,816
  • 4
  • 40
  • 68

1 Answers1

1

first label the count field as :

db.session.query(func.count(Tag.name).label('count'), Tag.name).group_by(Tag.name).limit(limit)

and then add a new shema as:

class TagCountSchema(ma.ModelSchema):
    name = fields.String()
    count = fields.Int(dump_only=True)
Jibin Mathew
  • 4,816
  • 4
  • 40
  • 68