I would like to use the "nested" url /customers/<id>/orders to create new orders using POST. I would like to get the related order's customer_id based on the request's url <id>.
Order model has a customer = ForgeinKey(Customer,..) field that relates to the Customer model.
My approach so far is:
- Creating an
OrderSerializer - Using
create()to create an Model object - Getting the customer id during creation from
self.context['request'].get_full_path(), which return the full url path - Getting the customer object based on the customer id using
customer_id = self.context['request'].get_full_path().split('/')[2]
customers = Customer.objects.get(id=customer_id)
- Assigning the
customers.idto the Order'scustomer_idfield
This solution works but seems extremely dirty. Is there a better way?
Let me know if any more details are needed.
Thanks!