Django ManyToManyField默认使用所有对象进行初始化

时间:2018-02-26 15:53:54

标签: django initialization manytomanyfield m2m

我有2个班,玩家和游戏。玩家可以拥有多个游戏,因此我们在玩家模型中使用m2m关系:

class Player(models.Model):
    store_user = models.OneToOnefield(User, unique=True, on_delete=models.CASCADE)
    games = models.ManyToManyField(Game)
    isDeveloper = models.BooleanField(default=False, blank=False)

我的问题是,当新玩家注册时,由于某种原因,他们会获得已添加到数据库中的所有游戏对象。我怎样才能让新玩家最初没有游戏呢?

来自views.py的用户注册:

def signup(request):
  if request.user.is_authenticated:
      return render(request, 'home.html')
  else:
      if request.method == 'POST':
          user = UserCreateForm(request.POST)
          if user.is_valid():
              user.save()
              temp_user = User.objects.get(username=user.cleaned_data.get('username'))
              s_user = Player(store_user=temp_user, isDeveloper=user.cleaned_data.get('developer'))
              s_user.save()
              return redirect('login')
      else:
          user = UserCreateForm()
      return render(request, 'signup.html', {'form': user})

1 个答案:

答案 0 :(得分:2)

对于多对多的字段,您需要使用中间表。有关详情,请点击https://medium.com/@adriennedomingus/django-adding-an-intermediate-model-to-a-manytomany-field-without-one-493ee52ba4a5

class Player(models.Model): games = models.ManyToManyField(Game)

class GamePlayer(models.Model): players = models.ForeignKey(Player, on_delete=models.CASCADE) games = models.ForeignKey(Game, on_delete=models.CASCADE)