Assign pk form URL to model's related field

115 Views Asked by At

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!

2

There are 2 best solutions below

0
On BEST ANSWER

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)
0
On

You can simply do this.

def create(self):
    customer_id = self.kwargs['id']
    customers = Customer.objects.get(id=customer_id)