Change Deck of Cards 3

Hello guys,

I want to be able to programmatically change the decks of certain cards based on search criteria

I found this forum post but it’s not working for me

https://forums.ankiweb.net/t/change-deck-of-cards/16647

this is what I have so far and the error I get is below:

import os

from anki.storage import Collection
from aqt import mw


def main():

    anki_home = r"C:\Users\asdf\AppData\Roaming\Anki2\User 1"
    anki_collection_path = os.path.join(anki_home, "collection.anki2")

    # load anki collection
    collection = Collection(anki_collection_path, log=True)

    anki_search_query = r"qwerqwerqwerqwer OR zxcvzxcvzxcvzxcv OR asdfzxcvzxcv"


    if anki_search_query:
        print("anki_search_query")
        print(anki_search_query)

        # returns iterable of note IDs based on query like in Anki browser search
        search = collection.find_cards(query=anki_search_query)
        # search = col.find_notes(query=anki_search_query)
    else:
        print("Anki search query empty")
        return

    deck_orig_id = 1660396300887
    deck_dest_id = 1660396331602

    mw.col.decks.setDeck(search, deck_dest_id)


    # save it
    collection.save()

    print()


if __name__ == "__main__":
    main()

error:

Traceback (most recent call last):
  File "Anki leetcode remove tags.py", line 88, in <module>
    main()
  File "Anki leetcode remove tags.py", line 65, in main
    mw.col.decks.setDeck(search, deck_dest_id)
AttributeError: 'NoneType' object has no attribute 'col'

it seems like in the initialization of mw, it gets set to None and I’m not sure how to fix that

It looks like your code is being ran before the main window (mw) is initialised. You should use a hook to run your code (either the hook main_window_did_init or profile_did_open should be appropriate here)

More information on hooks can be found here

The very first parts of the add-on docs should answer your questions (this in particular). Did you define an __init__.py file in the root of your add-on folder? You don’t need if __name__ == "__main__":

solved. it’s possible to call the method set_deck() directly from the collection object from the Anki python package