Reputation: 733
I am using Django-Tastypie.
I have a URL like
/api/v1/pic/?event=25&format=json
This returns all photos for ?event=25
. But I have certain other things that it should take into consideration.
Like an event which is private(ie: event.private=1
) it should do some kind of filtering on the photos that it returns. How do I implement it? Any pointers will be of great help.
Upvotes: 1
Views: 5467
Reputation: 3156
I landed here looking for more general Tastypie filtering, so I thought I'd add a bit more to @ge7600's answer.
If you want to filter on fields you can use any valid Django query syntax in the url. If I've exposed these fields for filtering:
class PicResource(ModelResource):
event = fields.ForeignKey(EventResource, 'event')
class Meta:
queryset = Pic.objects.all()
filtering = {
'event' : ALL_WITH_RELATIONS,
'date' : ALL,
'title' : ALL
}
ordering = ['date', 'event']
I can filter with the url parameters like:
/api/v1/pic/?event=25
/api/v1/pic/?title__contains=sunset
/api/v1/pic/?date__gte=2015-06-01&title__contains=wedding
If I read the docs more carefully I might have figured that out sooner...
Upvotes: 0
Reputation: 399
Can you be more specific? What kind of filters do you want.
For private event filters you can define a Boolean field in the model:
=====================Models=====================
class Event(models.Model):
private = models.BooleanField()
...
class Pic(models.Model):
event = models.ForeignKey(Event)
date = models.DateTimeField()
...
=====================Resources=====================
class PicResource(ModelResource):
event = fields.ForeignKey(EventResource, 'event')
class Meta:
queryset = Pic.objects.all()
filtering = {
'event' : ALL_WITH_RELATIONS,
'date' : ALL
}
ordering = ['date', 'event']
Then, you could query the resources:
Upvotes: 2
Reputation: 399
You just have to define resource.
from django.contrib.auth.models import User
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from myapp.models import Entry
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'auth/user'
excludes = ['email', 'password', 'is_superuser']
class EntryResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = Entry.objects.all()
list_allowed_methods = ['get', 'post']
detail_allowed_methods = ['get', 'post', 'put', 'delete']
resource_name = 'myapp/entry'
authorization = DjangoAuthorization()
filtering = {
'slug': ALL,
'user': ALL_WITH_RELATIONS,
'created': ['exact', 'range', 'gt', 'gte', 'lt', 'lte'],
}
Upvotes: -1