I have a case that I am curious about for a long, long time. Say I have 3 models:
class Product(models.Model):
manufacturer = models.CharField(max_length=100)
description = models.TextField(blank=True)
class PurchasedProduct(models.Model):
product = models.ForeignKey(Product)
purchase = models.ForeignKey('Purchase')
quantity = models.PositiveIntegerField()
class Purchase(models.Model):
customer = models.ForeignKey('customers.Customer')
products = models.ManyToManyField(Product, through=PurchasedProduct)
comment = models.CharField(max_length=200)
I have an API and client application written in some JavaScript framework. So now I need to communicate between them! I am not sure how should I handle this situation in DRF, naturally I would expect to get something like this when accessing /purchase/1/
{
"id": 1,
"customer": 1,
"comment": "Foobar",
"products": [
{
"id": 1,
"product": {
"id": 1,
....
},
....
},
....
]
}
So I created proper serializer specifying that products
field should use PurchasedProductSerializer
which in turn uses nested ProductSerializer
. It is fine cause I get all necessary info to, say, display what specific products where purchased and in what quantity during shopping using appropriate components in say React.
The problem for me is however when I need to POST
new PurchasedProduct
. I would expect the most convenient form to be:
{
"quantity": 10,
"purchase": 1,
"product": 1
}
As it carries all necessary info and has the smallest footprint. However I can't be accomplished using PurchasedProductSerializer
as it requires product
to be object instead of id
.
So my question here, is this a good approach (it seems very natural to me), should I use two separate serializers for GET
and POST
? Should I perform this differently? Could you point me to some best practices/books how to write APIs and client apps?