Question

I have the following Resource and am attempting to prepend a url to the api and get all the clubs for a manufacturer resource. Currently, I am just trying to get a response with all clubs (notice I just do a objects.all(), because I am just wanting data at this point, I'll filter it later). My issue is that when I hit the url, I do indeed get clubs, however, they aren't in json format, the result looks like this:

"[<Club: Club object>, <Club: Club object>]"

What do I need to add to the create_response so that it will return the json formatted object so that it can be used - basically, have it blow out the objects instead of leaving them as

"[<Club: Club object>]"

Here is what a club looks like:

{
  "_id" : "5275b295fa57952e260243e5|Fairway|1",
  "manufacturer" : "Adams",
  "head_material" : null,
  "image_url" : "https://blah.com",
  "year" : "0",
  "name" : "Tight Lies GT Xtreme Offset",
  "url" : "http://blah.com"
}

Here is the resource:

class ManufacturerResource(resources.MongoEngineResource):
    class Meta:
        queryset = documents.Manufacturer.objects.all().order_by('id')
        allowed_methods = ('get')
        resource_name = 'manufacturers'
        include_resource_uri = False

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<pk>[\w\d_.-]+)/drivers/$" % self._meta.resource_name, self.wrap_view('get_manufacturer_drivers'), name="api_get_manufacturer_drivers"),

    ]

    def get_manufacturer_drivers(self, request, **kwargs):
        drivers = documents.Club.objects.all().order_by('id')

        return self.create_response(request, drivers)
Was it helpful?

Solution

I ended up figuring this out after digging and digging. I couldn't find anything built in that did what I created. What I did was created a HelperMethod class with some static methods. Here is was I came up with:

class HelperMethods:
    @staticmethod
    def obj_to_dict(object):
        return_data = {}
        for property, value in vars(object).iteritems():
            return_data[property] = value

        return return_data['_data']

    @staticmethod
    def obj_to_list(objects):
        return_data = []
        for object in objects:
            return_data.append(HelperMethods.obj_to_dict(object))
        return return_data

Usage:

        return self.create_response(request, HelperMethods.obj_to_list(drivers))

Hope this helps someone.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top