views:

58

answers:

1

I am in a process of designing a client for a REST-ful web-service.

What is the best way to go about representing the remote resource locally in my django application?

For example if the API exposes resources such as:

  • List of Cars
  • Car Detail
  • Car Search
  • Dealership summary

So far I have thought of two different approaches to take:

  1. Try to wrangle the django's models.Model to mimic the native feel of it. So I could try to get some class called Car to have methods like Car.objects.all() and such.
    This kind of breaks down on Car Search resources.
  2. Implement a Data Access Layer class, with custom methods like:

    • Car.get_all()
    • Car.get(id)
    • CarSearch.search("blah")

    So I will be creating some custom looking classes.

Has anyone encoutered a similar problem? Perhaps working with some external API's (i.e. twitter?)

Any advice is welcome.

PS: Please let me know if some part of question is confusing, as I had trouble putting it in precise terms.

A: 

This looks like the perfect place for a custom manager. Managers are the preferred method for "table-level" functionality, as opposed to "row-level" functionality that belongs in the model class. Basically, you'd define a manager like this:

class CarAPIManager(models.Manager):
    def get_detail(self, id):
        return self.get(id=id)

    def search(self, term):
        return self.filter(model_name__icontains=term)

This could be used either as the default manager -- e.g., in your model definition:

class Car(models.Model):
    ...

    objects = CarAPIManager()

# usage
>>> Car.objects.search(...)

or you could just make it an additional manager, as a property of the class:

class Car(models.Model):
    ...

    api = CarAPIManager()

# usage
>>> Car.api.search(...)
Hm, but my model does not have a filter method, for example. I can only issue HTTP request to my rest-web server.
drozzy
I don't think I understand. True, the model lacks a filter method -- that's what the manager (``Car.objects``) has. If you want to handle an HTTP request, that would happen through a view. The view would handle the request and call the manager.