When developing a REST API using django and django rest framework, it seems to me that there's a step missing at the very end of this chain, especially if you'll design a python client of that API:
- define the model of your resources in django
- use DRF's serializers to send your resource over HTTP
- missing: deserialize your resource back in a python model
Let me give a simple example. I declare the following django model with a bit of business logic:
class Numberplate(models.Model):
number = models.CharField(max_length=128)
country_code = models.CharField(max_length=3)
def __repr__(self):
return f"{self.number} ({self.country_code})"
DRF is super powerful when it comes to building the API around that model. However, if I call that API from a python client, it seems that the best I can get as a response from that API will be a simple json without all the logic I might have written in my model (in this case, the __repr__
method), and I'll have to navigate through it as such.
Continuing my example, here is the difference with and without a proper deserializer:
# the best we can do without rewriting code:
>> print(api.get(id=3))
{"numberplate": "123ABC", "country_code": "BE"}
# instead of re-using my __repr__, which would be ideal:
>> print(api.get(id=3))
123ABC (BE)
Is there a clean way to stay DRY and write the logic only once?
I've thought about a couple of options which are not satisfactory in my opinion:
- write a django-model-agnostic Numberplate class and make your model class inherit from both
models.Model
and that class - import your django models in your client (like this)