我编写了一个函数来将 xml 文件中的数据保存到数据库。我正在使用两个模型,见下文。
模型.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
谢谢