2

I am facing issue on how to retrieve data of foreign key table.

My 2 models looks like these..

class Orders(models.Model):
    orderId = models.IntegerField()
    customer = models.ForeignKey(Customers,blank=True,null=True)

class Customers(models.Model):
    Domain= models.CharField(max_length=300, null=True ,blank=True)
    CustomerName= models.CharField(max_length=200,null=True,blank=True)

I want to list out all orders from Orders model and also CustomerName from Customers model through reference of customer_id to Customers Model

What should I write in my below views.py

class OrderList(APIView):
    authentication_classes = (authentication.TokenAuthentication,)
    def get(self,request):
             orders=Orders.objects.all()
             serializer = OrderSerializer(orders,many=True)
             return Response(serializer.data)
4
  • You have to explain more what you want if you wanna better answers. Commented Dec 27, 2013 at 7:02
  • I edited somewhat my question , which part you are not able to get? Commented Dec 27, 2013 at 7:07
  • "through reference of customer_id to Customers Model" Commented Dec 27, 2013 at 7:07
  • Customer.objects.values('id', "CustomerName") something like this? This will give you all the Customer's Name and id in dictionaries for example: [{"id"1: "CustomerName":"HI"},{"id"1: "CustomerName":"HELLO"}] Commented Dec 27, 2013 at 7:11

1 Answer 1

2

You can reference attributes of foreign key directly. In your case you can use

order.customer.CustomerName

to reference CustomerName for given order.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.