0

我有几个模型 - NodeLinkMap。地图有link_idnode_a_idnode_b_id字段。我为 显示一个表单,为Link2个表单显示Node。如何将输入的信息保存在Map将存储关系的模型中?

4

1 回答 1

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(...)
于 2013-04-07T21:47:52.590 回答