开发者

Best way to to create this field for my model

开发者 https://www.devze.com 2023-02-06 17:53 出处:网络
Hello everyone I just started with django and was wondering how to do the following behaivor in my models:

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.For开发者_开发知识库eignKey(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?


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....

0

精彩评论

暂无评论...
验证码 换一张
取 消