使用2个表进行xml解析

时间:2013-04-05 14:18:33

标签: python xml django xml-parsing django-views

我写了一个函数将xml文件中的数据保存到数据库。我使用的是两个模型,见下文。

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)

我的.xml文件是

 <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>  

我需要的是将xml数据保存到适当的字段中。从谷歌我学会了使用单个表进行配对,这里我不知道如何为“作者”表创建对象。

我尝试使用以下代码

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 

获得以下追溯

AttributeError at /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

由于

1 个答案:

答案 0 :(得分:0)

您的图书模型没有first_name

您需要创建一个作者对象,然后将作者保存为图书模型的外键。

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()

您的Author模型中可能需要另一列名为author_id

的列