我有几个模型 - Node
,Link
和Map
。地图包含link_id
,node_a_id
和node_b_id
字段。我正在为Link
显示一个表单,为Node
显示2个表单。如何将输入的信息保存在Map
模型中,该模型将存储关系?
答案 0 :(得分:0)
我假设您正在使用ModelForms,并且地图需要保存链接和节点。
首先,您需要保存此模型,然后保存地图模型。我还假设,link_id,node_a_id和node_b_id被定义为models.ForeignKey(Link)......
所以看起来像这样:
# somehwere on your views.py ...
def my_display_forms_view(request):
if request.method == 'POST':
na = Node()
nb = Node()
link = Link()
na_form = NodeForm(request.POST, instance=na)
nb_form = NodeForm(request.POST, instance=nb)
link_form = LinkForm(request.POST, instance=link)
if na_form.is_valid() and nb_form.is_valid() and link_form.is_valid():
na = na_form.save()
nb = nb_form.save()
link = link_form.save()
map = Map(link_id=link, node_a_id=na, node_b_id=nb)
# maybe here fill more fields for map
map.save()
# eventually do some more stuff
else:
... generate new unbound forms here
return render_to_response(...)