【问题标题】:How to Reverse Foreign key in python Flask-peewee如何在 python Flask-peewee 中反转外键
【发布时间】:2014-03-28 12:12:43
【问题描述】:

我正在使用Flask-peewee,并且有两个表用于类别和子类别,我想制作一个 api 来根据 JSON 中的类别列出所有子类别。 (反向外键)

所以如果我们有 5 个主要类别和 20 个子类别,我们需要在 5 个主要类别下列出 20 个子类别,所以我们应该只在 JSON 中显示 5 条记录。

例如:

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

模型.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

【问题讨论】:

    标签: python json flask peewee flask-peewee


    【解决方案1】:

    您可以使用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
    

    当然,您可以自定义以上内容以满足您的需求。如果您在子类别类中定义 related_name,则此方法有效:

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

    这是我用来解决这个问题的link to the example app;只需运行它,您就可以看到它是如何工作的。

    【讨论】:

    • 谢谢你本,你摇滚!
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 2016-10-27
    • 1970-01-01
    • 2020-11-26
    相关资源
    最近更新 更多