Anki Addon Programming - Reloading the card after changing fields
Note: I found this blog posts somewhere in my notes. Since I did not note, when did I write it, I posted it with the today's date.
When doing the changes to the notes programmatically, a lot of times I did not want to click on another note and then back in order to make the new data show in the field. While this is not problematic, if the changes are made in bulk, they are problematic, if the changes are made card by card.
The first case, when this happened was when I was doing the cards from the Anime script. My flow was listening to the Anime, correcting the readings and then generating reading cards from all the readings in the card. I did not want to pause the anime to frequently, so the upper problem was an actual problem
My original solution was to flush the card and reset the editor after the change. Which worked fine, as long as I was only doing the changes in the editor window, and not when I was adding cards.
fieldName = "" fieldValue = "" editor.note.__setitem__(fieldName, fieldValue) editor.note.flush() editor.mw.reset()
But this had two problems. First, I did use the function starting with double underscore, which is a bad precedent, since this is a way in python to indicate that this is a private function to other programmers. Since python by design does not really have private functions, this means that a person can still use it without a problem.
But the upper part would still be alright, as long as this is only for my personal user.
The second problem is, that this does not work for new cards. Which, when I started to finally go through the Heising Remembering the Kanji, became the problem. I did not want to add the card, just so I can change the card into something that I could use.
The new cards, before being added, have an card id of 0. The flush function checks for the id, and it only flushes the card, if the card id does not equal 0. Otherwise it throws the AssertionError. The function can be found in the note.py file, in the note class, under function name flush().
def flush(self) -> None: assert self.id != 0 self.col.backend.update_note(self.to_backend_note())
So I have tried to came up with a different way to do it. My first intuition was to check the Japanese addon. But while I have found the solution to the private function, I had not found the solution to the updating the card. So I was looking over the code in the editor, if there was any helpful function there, that I could use. And there I found the loadNoteKeepingFocus(). Testing it, it seems to work in the way, that I expected and it works.
So now the new code for this part looks like this:
fieldName = "" fieldValue = "" editor.note[fieldName] = fieldValue editor.loadNoteKeepingFocus()