diff --git a/anki/models.py b/anki/models.py index af979817a..c671ca07b 100644 --- a/anki/models.py +++ b/anki/models.py @@ -254,6 +254,24 @@ where mid = ?) and ord > ?""", self.id, ord) for c, t in enumerate(self.templates): t['ord'] = c + def moveTemplate(self, template, idx): + oldidx = self.templates.index(template) + if oldidx == idx: + return + oldidxs = dict([(id(t), t['ord']) for t in self.templates]) + self.templates.remove(template) + self.templates.insert(idx, template) + self._updateTemplOrds() + # generate change map + map = [] + for t in self.templates: + map.append("when ord = %d then %d" % (oldidxs[id(t)], t['ord'])) + # apply + self.flush() + self.deck.db.execute(""" +update cards set ord = (case %s end) where fid in ( +select id from facts where mid = ?)""" % " ".join(map), self.id) + # Model changing ########################################################################## diff --git a/tests/test_models.py b/tests/test_models.py index 5ee4bf616..b5cb4c05c 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -81,6 +81,15 @@ def test_templates(): f['Back'] = u'2' d.addFact(f) assert d.cardCount() == 2 + (c, c2) = f.cards() + # first card should have first ord + assert c.ord == 0 + assert c2.ord == 1 + # switch templates + m.moveTemplate(c.template(), 1) + c.load(); c2.load() + assert c.ord == 1 + assert c2.ord == 0 # removing a template should delete its cards m.delTemplate(m.templates[0]) assert d.cardCount() == 1