简体   繁体   English

Django ManyToManyField没有保存M2M关系

[英]Django ManyToManyField not saving m2m relationships

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: Game模型有一个返回其玩家的方法,因此我重写了Vote模型的save方法:

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). 但是,它似乎并未将任何玩家添加到voters字段中(并且db中的vote_voters表仍然为空)。

Obvious troubleshooting: the queryset is definitely not empty, the save method is definitely being called. 明显的故障排除:queryset绝对不是空的,肯定会调用save方法。

Your models.py 您的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 在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. 未经测试,但创建视图中的想法是先创建对象,然后保存m2m。 Check the form_valid method 检查form_valid方法

It turns out that this was an issue with the admin section. 原来,这是admin部分的问题。 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 @Selcuk的链接到此答案此答案解决了问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM