0

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:

  1. Creating an OrderSerializer
  2. Using create() to create an Model object
  3. Getting the customer id during creation from self.context['request'].get_full_path(), which return the full url path
  4. 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)
  1. Assigning the customers.id to the Order's customer_id field

This solution works but seems extremely dirty. Is there a better way?

Let me know if any more details are needed.

Thanks!

Charalamm
  • 1,547
  • 1
  • 11
  • 27

2 Answers2

0

From the create() method of the serializer, one can access the pk using

self.context['view'].kwargs['pk']

So the above code becomes:

customer_id = self.context['view'].kwargs['pk']
customers = Customer.objects.get(id=customer_id)
Charalamm
  • 1,547
  • 1
  • 11
  • 27
0

You can simply do this.

def create(self):
    customer_id = self.kwargs['id']
    customers = Customer.objects.get(id=customer_id)
Rahul Raj
  • 516
  • 7
  • 15