Django, bulk_create or bulk_update with manytomanyfield?

Viewed 100

With the following models,

class Song(models.Model):

    name = models.CharField(max_length=10)


class Album(models.Model):

    songs = models.ManyToManyField(Song, through=AlbumSong)


class AlbumSong(models.Model):
    song = models.ForeginKey(song)
    album = models.ForeginKey(album)

I want to do bulk_create albums with songs (following code doesn't work because songs field can't be set as it is)

albums = [
    Album(
        songs=[1,2]
    ),
    Album(
        songs=[3,5]
    )
]

Album.objects.bulk_create(albums)

I also want to bulk_update with songs set to list of values

albums = Album.objects.some_filter()

for album in albums:
    album.songs = [1,2]


Album.objects.bulk_update(albums)

I can do bulk_create on AlbumSong through table, but it's harder with bulk_update where you might have to remove some songs from albums. (you want to set songs to [1, 2] , you have to delete songs other than 1,2, if exsting albums have songs other than 1, 2)

1 Answers

So I ended up doing deleting and modifying

  • find all existing albums , and update them (Album.objects.some_filter().update())
  • find AllbumSongs where song is neither of [1,2] and delete them
  • bulk_create AlbumSongs with [1,2] with ignore_conflicts=True
Related