Django - How can I create POST with foreign key de

2019-07-15 18:07发布

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?

1条回答
女痞
2楼-- · 2019-07-15 18:49

Like this:

@api_view(['GET', 'POST'])

def object_list(request, myID):

    if request.method == 'POST':
        serializer = ObjectSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(id_users=myID)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
查看更多
登录 后发表回答