0

Hello everyone I just started with django and was wondering how to do the following behaivor in my models:

class Game(models.Model)
  characters_count = models.IntegerField(default=1) #basically i set to a choice of 1-3

class Match(models.Model)
 video=models.ForeignKey(Game)
 p1char1 = models.ForeignKey(Character)
 p2char1 = models.ForeignKey(Character)
 p1char2 = models.ForeignKey(Character)
 p2char2 = models.ForeignKey(Character)
 p1char3 = models.ForeignKey(Character)
 p2char3 = models.ForeignKey(Character)

video contains the instance game which Match relies on.

I need to create a constraint that the Character selected is from the given game and that the number of characters each player selects is limited by game as well.

Should I perform this on the Save method? or can I set these constraints some other way so the forms will be generated by the models accordingly without doing it manually.

Will the limitation on the characters (by the game) can be done on the definition of the model?

Yarin Miran
  • 3,241
  • 6
  • 30
  • 27

1 Answers1

0

for your characters you should create a Many to Many relation with your character Model.

Then override Match save() method to constrain the number of characters selected.

Another way would be to put this constraint in the clean() method of a modelform based on match : so they have a list to choose from (use a checkbox list widget) and if they select too much character, the form will relaod with the error message you'll put in clean()

To limit the character depending on the game, you can add another M2M relation between Character and Game ('allowed_in_game') : in the admin, you'll be able to choose the characters from a game.

Then, in the Match Modelform, you'll have to modifiy the ModelchoiceField showing characters to filter them to show only the ones which are related to the current Game.

Here's how (just borrowed from here) :

class Matchform(forms.ModelForm):
    class Meta:
        model = Match

     def __init__(self, game, *args, **kwargs):
         super(Matchform, self).__init__(*args, **kwargs)
         self.fields['character'].queryset = Character.objects.filter(allowed_in_game__in = game)

Then you can call your modified ModelForm like this :

Matchform(game)
Matchform(game,request.POST)
Matchform(game,instance=m)

You can see that everytime the "game" parameter is added, it should be a Game object for this example to work.

Hope this helps....

Community
  • 1
  • 1
Dominique Guardiola
  • 3,431
  • 2
  • 22
  • 22
  • Okay that sounds right but what about limiting the Characters to choose from? I want the character list to be from the specific game driven by the video member. Does this belongs to the FormModel or I can do that in the model as well ? (I can check it in the save() but I was wondering if I have something else I could do) – Yarin Miran Jan 22 '11 at 22:15