Django外键是一个尚未创建的模型

时间:2011-11-12 21:39:54

标签: django django-models django-forms

我想知道Django是否有办法将模型与另一个尚未创建的外键关键模型相关联。两个模型都将在同一个HTML页面中使用相同的ModelForm创建。

e.g。

class Team(models.Model):
    name = forms.CharField
    ...

class Player(models.Model):
    name = forms.CharField()
    key = forms.ForeignKey(Team)
    ...

基本上,我想知道这两个模型是否可以在一个HTML页面中放在同一个<form>...</form>中。

2 个答案:

答案 0 :(得分:1)

外键是对引用模型的主键的引用,因此目标需要存在。您需要保存第一个表单,然后在保存之前更新第二个表单上的引用。要从表单中获取模型实例而不保存到数据库,可以使用

instance = form.save(commit=False)

然后你需要自己保存实例

instance.save()

如果您使用的是多对多字段,则需要查看save_m2m

答案 1 :(得分:1)

您可能需要查看inlineformset的文档,它允许在同一视图中编辑模型的相关对象,另请参阅formsets

def manage_teams(request, team_id):
    team = Player.objects.get(pk=team_id)
    PlayerInlineFormSet = inlineformset_factory(Player, Team)
    if request.method == "POST":
        formset = PlayerInlineFormSet(request.POST, request.FILES, instance=team)
        if formset.is_valid():
            formset.save()
           # Do something.
    else:
        formset = PlayerInlineFormSet(instance=team)
    return render_to_response("manage_teams.html", {
        "formset": formset,
})

这是另一个例子:

from django.forms.models import inlineformset_factory
def new_team(request):
    PlayerInlineFormSet = inlineformset_factory(Team, Player)
    team= Team()
    if request.method == 'POST':
        form_team = TeamForm(request.POST, request.FILES, instance= team, prefix= 'team')
        form_player = PlayerInlineFormSet(request.POST, request.FILES, instance= team, prefix= 'players')
        if form_team.is_valid() and form_player.is_valid():
            form_team.save()
            form_player.save()
            return HttpResponseRedirect('/teams/%s/' % team.slug)
    else:
        form_team = TeamForm( instance= team,  prefix= 'team')
        form_player = PlayerInlineFormSet(instance= team, prefix= 'players')
    return render_to_response('Teams/new_team.html', {'form_team': form_team, 'form_player':form_player}, context_instance=RequestContext(request))