python - xml parsing using 2 tables -
i written function save data in xml file database.i using 2 models ,see below.
models.py
class author(models.model): first_name = models.charfield(max_length=30) last_name = models.charfield(max_length=40) email = models.emailfield() age = models.integerfield() class book(models.model): book_id=models.autofield(primary_key=true,unique=true) book_name=models.charfield(max_length=30) publisher_name=models.charfield(max_length=40) author=models.foreignkey(author)
my .xml file is
<book> <book_id>101</book_id> <book_name>python</book_name> <publisher_name>maxwell</publisher_name> <author_id>1002</author_id> <first_name>john</first_name> <last_name>dezosa</last_name> <email>john@gmail.com</email> <age>34</age> </book> <book> <book_id>102</book_id> <book_name>django</book_name> <publisher_name>technical</publisher_name> <author_id>1003</author_id> <first_name>josep</first_name> <last_name>raj</last_name> <email>joseph@gmail.com</email> <age>29</age> </book>
what required save xml data appropriate fields.from google learned paring using single table,here don't know how create object "author" table.
i tried below code
for books in xmldoctree.iter('book'): book_id = books[0].text book_name = books[1].text publisher_name = books[2].text author_id = books[3].text books.first_name = books[0].text books.last_name = books[1].text books.email = books[2].text books.age = books[3].text
getting following traceback
attributeerror @ /addxml/ first_name request method: post request url: http://localhost:8000/addxml/ django version: 1.3.7 exception type: attributeerror exception value: first_name exception location: /root/samples/demoapp/demoapp/views.py in addxml, line 106
thanks
your books model not have first_name
you need create author object, , save author foreign key book model.
for books in xmldoctree.iter('book'): book_id = books[0].text book_name = books[1].text publisher_name = books[2].text author_id = books[3].text first_name = books[4].text last_name = books[5].text email = books[6].text age = books[7].text author, _ = author.objects.get_or_create(id=author_id, defaults={'first_name': first_name, 'last_name': last_name, 'email': email, 'age': age}) author.save() book, - = book.objects.get_or_create(book_id=book_id, defaults={'book_name': book_name, 'published_name': publisher_name, 'author': author)}) book.save()
you might need column in author
model called author_id
Comments
Post a Comment