pythondjangodjango-shell

How to add multiple many to many data in django shell


I have a player instance who played three leagues. in the player model class, I set many to many fields with league class.

Now I want to add all 3 leagues to the player instance in Django shell.

class League(models.Model):
        league = models.CharField(max_length=20)

        def __str__(self):
            return self.league

    class Player(models.Model):
        name = models.CharField(max_length=30)
        league_played = models.ManyToManyField(League, default='Unknown')

Solution

  • Something along the following lines should work. Use the field's add method as outlined in the documentation:

    p = Player.objects.get(name=whatever)
    p.league_played.add(*League.objects.filter(league__in=['league_name1', 'ln2', 'ln3']))
    

    For a better django shell, I can recommend you django-extension's shell_plus which has some cool features like code completion or auto imports of all your models.