0

I have a model defined like so:

class Vote(models.Model):
    text = models.CharField(max_length=300)
    voters = models.ManyToManyField(CustomUser, blank=True)
    game = models.ForeignKey(Game, on_delete=models.CASCADE)

I want a vote to automatically add all players of its associated game to its list of voters, when it is created. The Game model has a method that returns its players, so I have overridden the save method of the Vote model:

def save(self, *args, **kwargs):
    super().save(*args, **kwargs) #As the docs state it must be saved before m2m elements can be added
    queryset = self.game.get_players
    for player in queryset:
        self.voters.add(player.id)

This does not work. It does not throw an error, and happily saves the model instance through the admin site. It does not, however, seem to add any of the players to the voters field, (and the vote_voters table remains empty in the db).

Obvious troubleshooting: the queryset is definitely not empty, the save method is definitely being called.

Alex
  • 2,270
  • 3
  • 33
  • 65

2 Answers2

1

Your models.py

class Vote(models.Model):
   text = models.CharField(max_length=300)
   voters = models.ManyToManyField(CustomUser, blank=True)
   game = models.ForeignKey(Game, on_delete=models.CASCADE)

in forms.py

from django import forms
from your_app.models import Vote

class VoteForm(forms.ModelForm):
    class Meta:
      model = Vote
      fields = ('text', 'game')

And a class based create view

from django.views.generic.edit import CreateView
from your_app.models import Vote
from your_app.forms import VoteForm

class VoteCreate(CreateView):
   model = Vote
   form_class = VoteForm

   def form_valid(self, form):
     obj = form.save(commit=True)
     obj.voters = obj.game.get_players
     # or maybe this 
     # obj.voters.add([game.player for game in obj.game.get_players])
     obj.save()
     return super().form_valid(form)

Not tested but the idea in the create view is that you first create the object and then save the m2m. Check the form_valid method

Dimitris Kougioumtzis
  • 2,339
  • 1
  • 25
  • 36
1

It turns out that this was an issue with the admin section. Using the exact save method shown in the question worked perfectly when submitted through a form. @Selcuk's link to this answer this answer solved the problem

Alex
  • 2,270
  • 3
  • 33
  • 65