开发者

Mimic remote API or extend existing django model

开发者 https://www.devze.com 2022-12-28 19:24 出处:网络
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?

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.


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(...)
0

精彩评论

暂无评论...
验证码 换一张
取 消