How to return Random items from a Mongodb Resource

35 views
Skip to first unread message

Anuj Chauhan

unread,
Feb 24, 2014, 7:58:23 AM2/24/14
to django...@googlegroups.com
Hi Friends,

I need to return random items from a tastypie resource which is a resources.MongoEngineResource.

I have already tried using MyClass.objects.all().order_by('?'), but it simply keep returning the same rows always. Following is the code of my resource.

class MViewSubResponseRandomResource(resources.MongoEngineResource):
    class Meta:
        queryset = SubResponse.objects.all().filter(asset_type='Photo').order_by('?')
        resource_name = 'mview/random'
        allowed_methods = ['get']
        authentication = SillyAuthentication()
        authorization = SillyAuthorization()

    def dehydrate(self, bundle):
        resource_uri = self.get_resource_uri(bundle)
        bundle.data = {}
        bundle.data['id']=bundle.obj.id
        bundle.data['file_url']=bundle.obj.file_url
        bundle.data['action_type']=bundle.obj.action_type
        bundle.data['asset_type']=bundle.obj.asset_type
        bundle.data['resource_uri']=resource_uri
        bundle.data['end_date']=bundle.obj.end_date
        return bundle
    
    def get_object_list(self, request):
        workgroup_id=request.REQUEST['wid']
        superset_limit=1000
        subresponses = SubResponse.objects.all().filter(asset_type='Photo', rejected=False, work_group_id=workgroup_id).order_by('?')[:superset_limit]
        return subresponses



Regards,
Anuj

Camilo Torres

unread,
Feb 24, 2014, 10:01:31 PM2/24/14
to django...@googlegroups.com
On Monday, February 24, 2014 8:28:23 AM UTC-4:30, Anuj Chauhan wrote:
Hi Friends,

I need to return random items from a tastypie resource which is a resources.MongoEngineResource.

I have already tried using MyClass.objects.all().order_by('?'), but it simply keep returning the same rows always. Following is the code of my resource.
Hello,

You should use the Python's built-in random module. See random.sample()

Regards,
Camilo
Reply all
Reply to author
Forward
0 new messages