Django Rest Framework — Writing Serializers that Differ From Your Internal Data Model
No matter how hard we try to get our data model correct (and even if we’ve done so!) sometimes by the time we need to use it, either for a public-facing API or an internal one, we need things to look a little different. Django Rest Framework(DRF) has some useful tools for allowing us to build serializers based on our models that differ somewhat from how we’ve defined things internally.
For our example, we’ll say we have a data model that looks, in part, like this:
class Item(models.Model):
name = models.CharField(max_length=255)
...class Offer(models.Model):
item = models.ForeignKey(Item)
...class Purchase(models.Model):
offer = models.ForeignKey(Offer)
...
If we want to allow users to access Item
s via the API, we may add an ItemSerializer
that leverages DRF’s ModelSerializer functionality, and looks like this, to start:
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('name',)
Below are just two of the most common ways I’ve seen folks override their external data models to differ from internal ones. Other things you’re trying to accomplish that you’re not sure how…