I wonder how can I create object POST with defined ID. Let's assume that I have for instance table User
with columns id
,name
and table Object
with columns id
,id_users
,sth
where id_users
is a foreign key of id
from User
table. I would like to have such URL /users/{id}/object
and I would like to create object for user with defined ID in URL.
For example this is my URL /users/1/object
(url(r'^users/(?P<myID>[0-9]+)/object/$', views.UserObject)
- should be okey) and body of POST:
{
"id": 2,
"sth": 123
}
In this case it should be added to my database:
{
"id": 2,
"id_users": 1,
"sth": 123
}
For User
with id
equals 1
we have created object
with id
equals 2
and sth
equals 123.
I don't know what my view should look like?
I always did POST
in this way:
@api_view(['GET', 'POST'])
def ObjectList(request):
if request.method == 'POST':
serializer = ObjectSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
I have deleted duplicated posts, because I have explained here how my database and relations between tables look like. I also specified what I would like to achieve. Any suggestions how can I deal with this?
Like this:
@api_view(['GET', 'POST'])