[英]How to Reverse Foreign key in python Flask-peewee
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. 我正在使用Flask-peewee,并且类别和子类别有两个表,我想制作一个api以基于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. 因此,如果我们有5个主要类别和20个子类别,则需要列出5个主要类别下的20个子类别,因此我们只应在JSON中显示5条记录。
For instance: 例如:
[{“name”: “medical”,subCategories: [{“name”:”Medical Dental Tourism”},{“name”:”another”}]},{“name”: “Restaurants”,subCategories: [{“name”:”Cafes”},{“name”:”another”}]}]
Models.py 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 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
You can use prepare_data()
to customize what the API outputs, as follows: 您可以使用prepare_data()
来自定义API的输出,如下所示:
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: 如果您在子类别类中定义了related_name
,则此方法有效:
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. 只需运行它,便可以看到它的工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.