flask-restless
flask-restless copied to clipboard
Allow include/exclude columns in collections only or individual instances only
for example, i have a Topic class:
class Topic:
id = Column()
user = Column(Integer, ForeignKey())
title = Column()
replies = Column(Integer, ForeignKey())
content = Column()
publish_tm = Column()
then, i create the api: topic_api = manager.create_api(Topic)
How to implement this requirement:
- when i visit http://host:port/api/topic, I want the response of topics do not include content & replies
- when I visit http://host:port/api/topic/
, I want the response of topic include content & replies. - If i want query topics of a user by username, How can i make the query?
In other words, you want to be able to specify both the columns to include when making a GET
request to the complete collection at api/topic
and the columns to include when making a GET
request to a single instance at api/topic/1
. Is that right? That feature does not yet exist, though I'm happy to review any pull requests for it.
I think your final question is a separate issue, namely allowing more complex search queries (by filtering on fields of related models), which I am not necessarily eager to add. Please create a separate issue (with a descriptive title) which describes the functionality you want.
question 3 is solved by filters. Thanks.
I'd like to leave this open, because this is still a feature request for specifying include/exclude columns on both a per collection and per instance basis.
Indeed, I would also like to be able to define different include/exclude columns based on whether the request is for a collection or individual resource.
so GET
to /api/users
shows id
, username
, email
for example, but a GET
to /api/users/2
would give me a different set of fields.
I've made a start on this and want to post this commit to see if this is heading in the right direction or is acceptable. Will require some changes to the existing unit tests of course.
commit is: 2f4e462b81e67624af889fcd633cbdef837ae5ef
This can now be fixed by defining a custom serializer class, introduced in pull request #510, something like this (untested) code.
class MySerializer(DefaultSerializer):
def serialize(instance, only=None, *args, **kw):
old_exclude = self.exclude
try:
self.exclude += [...]
result = super(MySerializer, self).serialize(instance, only=only, *args, **kw)
finally:
self.exclude = old_exclude
return result
def serialize_many(instances, only=None, *args, **kw):
# do something similar here
APIManager.create_api(Person, serializer_class=MySerializer)
It's not a great solution, especially since self.exclude
is undocumented, but I believe it should work. There may be other workarounds as well.
This needs to be added to the documentation and probably as an example in the examples/
directory as well.