如何使用带有内联模型的modelformset?

时间:2012-08-24 07:43:56

标签: python django django-forms

说我有一个类似的模型:

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_teamaway_team转换为CharFields(而不是当前的下拉列表),同时保持它们是单独的模型之外,这是可行的。如何将内联模型formset添加到模型formset中以实现此目的?

1 个答案:

答案 0 :(得分:0)

inlinemodelformset不起作用,因为Game有外国队Team。

inlinemodelformset可以显示通过ForeignKey连接到另一个模型的模型列表。例如,如果A.b是FK到B,则可以为B创建A的inlinemodelformset。

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

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 autocompletion