In straight Django, you can access random model instances by:
randinst = MyModel.objects.order_by('?')
Note: Though there are performance issues with this, I have tested with the sqlite backend and I do get really random results for up to 100000 tries. Since my app does not require significant performance beyond this, I am not concerned about other backends.
What I wish to accomplish is this: A client makes a request, /api/v1/mymodel/?limit=10
, and gets a random set of ten rows from MyModel via tastypie just like you would get running the above snippet 10 times. It then makes the same request, and receives 10 different (within the limits of probability) random rows.
Note: I have tried requesting /api/v1/mymodel/?ordering='?'
and all resonable variants thereof to no avail. Also unhelpful is setting MyModelResource.Meta.ordering = ['?']
Is there any way to accomplish my goal with tastypie? Are there other solutions to try? Thanks.
Answer courtesy of on #tastypie.
Set the queryset of the model as follows:
class MyModelResource(ModelResource):
class Meta:
queryset = MyModel.objects.all().order_by('?')
The key here is to use objects.all().order_by
not just objects.order_by
.