I want to limit the options of ‘winner’, which is a foreign key to the Jugador model, to the foreign keys of the ‘playerA’ and ‘playerB’ fields, which also point to the Jugador model. I guess I need to somehow access the instance of the Game model the form was created with in order to do a proper query set.
the form in forms.py:
class ganadorForm(ModelForm):
class Meta:
model = Juego
fields = ['ganador', 'jugadorA', 'jugadorB', 'torneo', 'ronda']
widgets = {
'ganador': ModelChoiceField(queryset=Jugador.objects.filter(Q(fields['jugadorA']) | Q(fields['jugadorB'])), to_field_name='nombre')
}
the model in models.py:
class Juego(models.Model):
torneo = models.ForeignKey(Torneo, on_delete=models.CASCADE, null=False)
ronda = models.ForeignKey(Ronda, on_delete=models.CASCADE, null=False)
jugadorA = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, related_name='jugadorA')
jugadorB = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, related_name='jugadorB')
ganador = models.ForeignKey(Jugador, on_delete=models.SET_NULL, null=True, default=None, related_name='ganador')
I have tried other approaches to forms.py:
class ganadorForm(ModelForm):
class Meta:
model = Juego
fields = ['ganador', 'jugadorA', 'jugadorB', 'torneo', 'ronda']
def __init__(self, *args, **kwargs):
super(ganadorForm, self).__init__(*args, **kwargs)
self.fields['ganador'].queryset = Jugador.objects.filter(Q(id=self.instance.jugadorA.id) | Q(id=self.instance.jugadorB.id))