1

假设我有一个模型:

class Team(models.Model):
    name = models.CharField(max_length=20)

class Game(models.Model):
    title = models.CharField(ma_length=20)
    home_team = models.ForeignKey(Team)
    away_team = models.ForeignKey(Team)

然后在我看来,我有:

def manage_games(request):
     GameFormSet = modelformset_factory(Game, extra=1)
     game_forms = GameFormSet(request.POST or None,
                                 queryset=Game.objects.all())
     if request.method == "POST":
         if game_forms.is_valid():
            game_forms.save()
            game_forms = GameFormSet(queryset=Game.objects.all())                 

     return render(request, "admin_dashboard/manage_games.html", locals())

这可以正常工作,除了我希望能够将home_teamandaway_team变成 CharFields(而不是现在的下拉菜单),同时还能将它们保持为单独的模型。如何将内联模型表单集添加到模型表单集中以使其成为可能?

4

1 回答 1

0

内联模型表单集不起作用,因为 Game 有外键团队。

inlinemodelformset 可以显示通过 ForeignKey 连接到另一个模型的表单列表。例如,如果 Ab 是 B 的 FK,则可以为 B 制作 A 的内联模型形式集。

但是,您仍然可以添加几个字段来更改主/客队名称:

from django import forms

from models import Team, Game    


class GameUpdateForm(forms.ModelForm):
    home_team_name = forms.CharField(max_length=20)
    away_team_name = forms.CharField(max_length=20)

    def save(self):
        obj = super(GameForm, self).save()

        if not obj.home_team_id:
            obj.home_team = Team()
        obj.home_team.name = self.cleaned_data.get('home_team_name')
        obj.home_team.save()

        if not obj.away_team_id:
            obj.away_team = Team()
        obj.away_team.name = self.cleaned_data.get('away_team_name')
        obj.away_team.save()

        return obj
    class Meta:
        model = Game
        exclude = ('home_team', 'away_team')

并让modelformset使用它:

GameFormSet = modelformset_factory(Game, form=GameForm, extra=1)

您可能还想添加CharField 自动补全。

于 2012-08-24T08:48:35.550 回答