Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django tastypie, possible to return only metadata for a query

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?

like image 310
wobbily_col Avatar asked Aug 23 '13 10:08

wobbily_col


People also ask

What is tastypie in Django?

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.

How does queryset work in Django?

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.

How do I retrieve objects from the database in Django?

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.

How do I create an API in Django?

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:


1 Answers

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

like image 115
Arsh Singh Avatar answered Oct 18 '22 09:10

Arsh Singh