-1

我编写了一个函数来将 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

谢谢

4

1 回答 1

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

于 2013-04-05T14:20:43.713 回答