来自ManyToMany的Django模型表单集不接受查询集

92dk7w1h  于 2023-01-31  发布在  Go
关注(0)|答案(1)|浏览(126)

我有一个名为Game的模型,它有一个ManyToMany字段。

consoles = models.ManyToManyField('Console', through='GameConsole')

ManyToMany具有一些附加属性

class GameConsole(models.Model):
    game            = models.ForeignKey(Game, on_delete=models.CASCADE)
    console         = models.ForeignKey(Console, on_delete=models.CASCADE)
    released        = models.DateTimeField    
    exclusive       = models.BooleanField(default=False)

我有一个页面,我想在那里创建/编辑这些关系。

#forms.py
class GameConsoleForm(ModelForm):
    class Meta:
        model = GameConsole
        fields = ['console', 'released', 'exclusive']

#to prevent the submission of consoles with the same id (taken from django topics forms formsets)
class BaseGameConsoleFormSet(BaseFormSet):
    def clean(self):
        """Checks that no two alias have the same name."""
        if any(self.errors):
            # Don't bother validating the formset unless each form is valid on its own
            return
        console_ids = []
        for form in self.forms:
            if self.can_delete and self._should_delete_form(form):
                continue
            console= form.cleaned_data.get('console')
            if console in console_ids:
                raise ValidationError("Consoles in a set must be different.")
            console_ids.append(console)

NewGameConsoleFormSet = modelformset_factory(GameConsole, form=GameConsoleForm, formset=BaseGameConsoleFormSet, extra=1, can_delete=True)
GameConsoleFormSet = modelformset_factory(GameConsole, form=GameConsoleForm, formset=BaseGameConsoleFormSet, extra=0, can_delete=True)

创建多个游戏控制台的工作很好。问题是在版本。在视图上,当我做以下操作:formset = GameConsoleFormSet(queryset = game_consoles)我得到了下面的错误__init__() got an unexpected keyword argument 'queryset',这很奇怪,因为我已经在另一个模型(普通表,而不是ManyToMany)中使用了这个逻辑,并且它工作正常。
全视图:

def mng_game(request, game_id):

    #get game and verify if it exists
    game = Game.objects.filter(id = game_id).first()
    if not game:
        request.session['error_code'] = 33
        return redirect('error')

    game_consoles = game.consoles.all()
    form = GameForm(instance = game)

    if game_consoles :
        #TODO understand why this does not accept queryset
        formset = GameConsoleFormSet(queryset = game_consoles)
    else:
        formset = NewGameConsoleFormSet()

    consoles = Console.objects.all()
    context = {
        'form':form,
        'game': game,
        'formset': formset,
        'consoles': consoles
    }

    #change details from the Game
    if 'name' in request.POST:
        #update game

    return render(request, 'games/mng_game.html', context)

我的问题是:是我做错了什么,还是ManyToMany模型表单集不支持用于编辑的查询集?

eblbsuwk

eblbsuwk1#

您需要继承BaseModelFormSet类而不是BaseFormSet,因此:

class BaseGameConsoleFormSet(BaseModelFormSet):
    ...

相关问题