Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining filters into one query in Tastypie [duplicate]

Possible Duplicate:
Django Tastypie Advanced Filtering: How to do complex lookups with Q objects

I have a tastypie modelRseource that looks like this:

class TaggedResource(ModelResource):
    tags = ListField()
    user = fields.ForeignKey(UserProfileResource, 'user')

    class Meta:
        queryset = Media.objects.all().order_by('-timestamp')
        authorization = MediaAuthorization()
        detail_allowed_methods = ['get', 'post', 'put', 'delete','patch']

    filtering = {
        #'user': ALL_WITH_RELATIONS,
        #exact is date, lt is less than lte less than equal to, etc
        'timestamp': ['exact', 'range', 'lt', 'lte', 'gte', 'gt'],
        'social_source': ALL,
        'media_type': ALL,
        'comment': ['exact', 'startswith', 'endswith', 'contains'],
        'media_text': ['exact', 'startswith', 'endswith', 'contains'],
    }

I need to have an OR operator between filters and would love to combine the query into one parameter. For example, I want to return objects that contain the word "test" filtering from the comment field OR media_text field.

This would be ideal: http:mysite.com/api/v1/tagged?q=test

where 'q' performs an OR filter for both fields.

Is this doable?

UPDATE: Here is what I am working on with advanced filters but am not really sure how to get an OR statement:

def build_filters(self, filters=None):
    if filters is None:
        filters = {}

    orm_filters = super(TaggedResource, self).build_filters(filters)

    if 'q' in filters:
        orm_filters['comment__contains'] = filters['q']
        orm_filters['media_text__contains'] = filters['q'] 
    return orm_filters  
like image 647
bevinlorenzo Avatar asked Jul 27 '12 22:07

bevinlorenzo


2 Answers

You're doing the right thing by overriding build_filters, you can use django's Q class for AND/OR queries, I have answered a similar question here

Tastypie filtering with multiple values

and here's another interesting one:

Tastypie Negation Filter

like image 181
Hedde van der Heide Avatar answered Nov 04 '22 10:11

Hedde van der Heide


I would suggest looking at Advanced Filtering even though I' not sure it is doable. But if you override build_filters, you have access to the whole Resource and possible could define such filters which go across more than field.

like image 32
Alex Botev Avatar answered Nov 04 '22 09:11

Alex Botev