Skip to content
Advertisement

DRF – Relate an object to another using views, serializers and foreign key

Basically I have two models with one-to-one relationship. And I want retrieve information from one, when I call the other.

My models:

JavaScript

So I can just call an POST and create an Customer, that customer will have id, first_name and last_name. For now everything is working.

But when I try to call my endpoint to create an CurrentAccount informing my Customer to relate, nothing happens.

My input:

JavaScript

The output that I expected:

JavaScript

The output that I received:

JavaScript

As you can see, Django are ignoring the relationship (In the database the field ‘customer_account_id’ is null too, so isn’t just an problem with my return).

Here is my serializers:

JavaScript

And my views to create the CurrentAccount:

JavaScript

So I basically want to understand how the relationships works on Django and how to handle with DRF context, using serializers. I already looked the docs, but I still not understanding.

Advertisement

Answer

The problem is with the CurrentAccountSerializer serializer, you set the customer_account field as read only. You should also use two serializers with CurrentAccount, the first to list existing instances and the second to create new ones.

serializers

JavaScript

views

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement