Question

I'm using Flask-peewee and there are two tables for categories and Subcategories,I'd like to make an api to list all subcategories Based on the category in JSON. (reverse foreign key)

So if we have 5 main Categories & 20 Subcategories, we need to list 20 subcategories under 5 main categories, so we should only display 5 records in JSON.

For instance:

[{“name”: “medical”,subCategories: [{“name”:”Medical Dental Tourism”},{“name”:”another”}]},{“name”: “Restaurants”,subCategories: [{“name”:”Cafes”},{“name”:”another”}]}]

Models.py

class Category(db.Model):
    __tablename__ = 'category'
    id = CharField(primary_key=True)
    name= CharField()

    def __unicode__(self):
        return self.image

class Subcategory(db.Model):
    __tablename__ = 'subcategory'
    id = CharField(primary_key=True)
    parent_id = ForeignKeyField(db_column='parent_id', rel_model=Category )
    name= CharField()

api.py

class CategoryResource(RestResource):
    exclude = 'created_at'

class SubcategoryResource(RestResource):
    exclude = 'created_at'
    include_resources = {'parent_id': CategoryResource} #I need this to be backwards
Was it helpful?

Solution

You can use prepare_data() to customize what the API outputs, as follows:

class CategoryResource(RestResource):
      def prepare_data(self, obj, data):
            data["subcategories"] = []
            for item in obj.subcategories:
                data["subcategories"].append({"name" : item.name})
            return data

Of course, you can customize the above to fit your needs. This works if you define a related_name in your subcategories class:

class Subcategory(db.Model):
       name = CharField()
       category = ForeignKeyField(Category, related_name = 'subcategories')

Here's a link to the example app that I used to figure this out; just run it and you can see how it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top