I have a Django Tastypie API set up.
I would like to query the database for the count of objects that match a name.
Is this possible on an existing model resource, or do I need to set up a new resource to handle this specific case? (This data is usually returned in the metadata part of the result? Is there an option just to return that from the paramaters?)
So if my url is usually like this:
http://127.0.0.1:8000/api/v1/library/?name__icontains=ABC
Can I add a parameter or change the url so that it only returns the metadata (I only want the number of libraries returned that have a name containing "ABC") rather than all the objects?
Tastypie is a webservice API framework for Django. It provides a convenient, yet powerful and highly customizable, abstraction for creating REST-style interfaces. Add tastypie to INSTALLED_APPS.
The first time a QuerySet is evaluated – and, hence, a database query happens – Django saves the query results in the QuerySet ’s cache and returns the results that have been explicitly requested (e.g., the next element, if the QuerySet is being iterated over). Subsequent evaluations of the QuerySet reuse the cached results.
Django will complain if you try to assign or add an object of the wrong type. To retrieve objects from your database, construct a QuerySet via a Manager on your model class. A QuerySet represents a collection of objects from your database. It can have zero, one or many filters. Filters narrow down the query results based on the given parameters.
Tastypie is a webservice API framework for Django. It provides a convenient, yet powerful and highly customizable, abstraction for creating REST-style interfaces. Add tastypie to INSTALLED_APPS. Create an api directory in your app with a bare __init__.py. Create an <my_app>/api/resources.py file and place the following in it:
You can pass in a get param:
http://127.0.0.1:8000/api/v1/library/?name__icontains=ABC&meta_only=true
and add this method to your resource:
def alter_list_data_to_serialize(self, request, data):
if request.GET.get('meta_only'):
return {'meta': data['meta']}
return data
documentation : http://django-tastypie.readthedocs.org/en/latest/resources.html#alter-list-data-to-serialize
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With