kerrickstaley / genanki

A Python 3 library for generating Anki decks
MIT License
1.99k stars 150 forks source link

All cards added to the first deck name when multiple decks are added to a package. #18

Closed josegaert closed 5 years ago

josegaert commented 5 years ago

Dear KerrickStaley,

Thank you for sharing your library. I think I might have found an issue.

Example code:

data = {
    'deck1':
    [{
    'a': 'content deck 1 a1',
    'b': 'content deck 1 b1'
    },
    {
    'a': 'content deck 1 a2',
    'b': 'content deck 1 b2'
    }],
    'deck2':
     [{
    'a': 'content deck 2 a1',
    'b': 'content deck 2 b1'
    },
    {
    'a': 'content deck 2 a2',
    'b': 'content deck 2 b2'
    }],
    'deck3':
     [{
    'a': 'content deck 3 a1',
    'b': 'content deck 3 b1'
    },
    {
    'a': 'content deck 3 a2',
    'b': 'content deck 3 b2'
    }]  
}

# Create the model
a_to_b = genanki.Model(
    2043134337, # unique identifier
    'a-to-b', # human readable name
    fields = [ 
    {'name': 'a'},
    {'name': 'b'},
    ],
    templates=[
    {
      'name': 'Card 1',
      'qfmt': '{{a}}',
      'afmt': '{{FrontSide}}<hr id="answer">{{b}}',
    },
    ]
)

decks = []
for deck_name in data:
    deck = genanki.Deck(
      2043134340,
      deck_name
    )

    # Add the notes
    for note in data[deck_name]:
      note = genanki.Note(
        model=a_to_b,
        fields=[note.get('a',''),
                note.get('b',''),
               ])
      deck.add_note(note)
    decks.append(deck)

# Create the file
genanki.Package(decks).write_to_file('output.apkg')

When I then load this apkg file into Anki, Anki adds all 6 cards that should be in deck1, deck2 and deck3 into only deck1.

sciencemanx commented 5 years ago

@kerrickstaley, @josegaert: It looks like the reason for this is that genanki writes multiple collections rows (one for each deck) to the apkg database instead of packing them all into a single collection row.

sciencemanx commented 5 years ago

A potential fix could be instead of inserting into the col table for each deck in deck.write_to_db, insert the default deck (is this required) once in pkg.write_to_db. Then, in each deck.write_to_db, select the decks column from col append the decks info to that field and then update it in the col table.

kerrickstaley commented 5 years ago

@sciencemanx makes sense. Want to take a stab at a PR? :)

sciencemanx commented 5 years ago

Yah -- I should have some time over the weekend to give it a shot.

sciencemanx commented 5 years ago

PR submitted and complete #20. Please review

kerrickstaley commented 5 years ago

This bug is fixed in version 0.6.4 (https://github.com/kerrickstaley/genanki/commit/53bc7b4e1be3f19af022ef293faa0040bc5c35ee).

Karl2222 commented 3 years ago

Hello sciencemanx,

I got the issue again. But the behavior is different

"When I then load this apkg file into Anki, Anki adds all 6 cards that should be in deck1, deck2 and deck3 into only deck3."