Django - 如何在URL中定义外键创建POST? [英] Django - How can I create POST with foreign key defined in URL?
问题描述
我想知道如何使用定义的ID创建对象POST。我们假设我有一个例子表用户
与列 id
,名称
和表对象
与列 id
, id_users
, sth
其中 id_users
是 id
的外键用户
表。我想要这样的URL / users / {id} / object
,我想在URL中为用户定义ID创建对象。
例如这是我的URL / users / 1 / object
( url(r'^ users /(?P< myID& 0-9] +)/ object / $',views.UserObject)
- 应该是okey)和POST的正文:
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
}
对于用户
与 id
等于 1
我们创建了
对象
与 id
等于 2
和 sth
等于123.
For User
with id
equals 1
we have created object
with id
equals 2
and sth
equals 123.
我不知道我的看法应该是什么样的?
我一直以这种方式执行 POST
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?
推荐答案
像这样:
@api_view(['GET','POST'])
@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)
这篇关于Django - 如何在URL中定义外键创建POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!