import os from mtgweb.lib.mtg import mtg, database from mtgweb.analyzer.models import Card, CardType, Attribute, Deck, Included class LookupDB(database.Database): def getCard(self, name): return Card.objects.get(name=name) def findCard(self, name): for card in Card.objects.filter(name__icontains=name): yield card def dbimport(): db = database.TextDB('lib/mtg/db.txt') for c in db.findCard(): print c try: card_type = CardType.objects.get(name=c.type) except: card_type = CardType.objects.create(name=c.type) card = Card(name=c.name, type=card_type,cost=c.cost, power=c.power, toughness=c.toughness) card.converted_cost = c.cost.converted() card.rarity = c.rarity card.text = "\n".join(c.text) card.save() attributes = [] for a in c.attributes: try: attr = Attribute.objects.get(name=a) except: attr = Attribute.objects.create(name=a) card.attributes.add(attr) def deckimport(): db = LookupDB() for filename in [n for n in os.listdir('lib/mtg/decks') if n.endswith('.txt')]: d = mtg.Deck() d.load('lib/mtg/decks/' + filename, db) name = filename.split('.')[0] print "Importing deck '{0}'".format(name) deck = Deck(name=name) deck.save() for card in d: try: c = Included.objects.get(deck=deck, card=card) except: c = Included(deck=deck, card=card) c.count += 1 c.save() dbimport() deckimport()