将json数据插入MySQL数据库

时间:2013-04-03 15:06:02

标签: django json django-models django-forms django-views

1.我想将数据库(mysql)中的数据保存为.json文件格式。

Models.py

class Author(models.Model):
    author_id = models.AutoField(primary_key=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age=models.IntegerField()

    class Meta:
    db_table=u'Author'

    def __unicode__(self):
        return u"%d %s %s %s %d" % (self.pk, self.first_name, self.last_name, self.email,self.age)



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)

    class Meta:
        db_table = u'Book'

    def __unicode__(self):
        return u'%d %s %s' % (self.pk, self.book_name, self.publisher_name)

views.py是

def addbook(request):

    log.debug("test....")
    if request.POST:

        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        email = request.POST.get('email')
        age = request.POST.get('age')

    author = Author(first_name = first_name,last_name = last_name,email=email,age=age)
        author.save()

        book_name = request.POST.get('book_name')
        publisher_name = request.POST.get('publisher_name')
        author_info = Author.objects.latest('author_id')

        log.debug("test:%s",author_info.author_id)

    book=Book(book_name=book_name,publisher_name=publisher_name,author_id=author_info.author_id)
    book.save()
    return redirect('/index/')
    else:
        return render_to_response('addbook.html',context_instance=RequestContext(request))

1)在views.py中,使用addbook函数将相关数据添加到数据库中。

2)我必须在每次输入后将数据库内容存储到json文件中。

3)我可以获得相同代码的帮助。

1 个答案:

答案 0 :(得分:0)

This link解释了如何序列化Django模型。您必须在模型代码中添加类似的内容:

from django.core import serializers

class Book(models.Model):
    ...
    def serialize(self): 
        JSONSerializer = serializers.get_serializer("json")
        json_serializer = JSONSerializer()  
        with open("/path/to/file/file.json", "w") as out:
            json_serializer.serialize([self], stream=out)

如果要序列化模型的特定实例,则[self]周围的方括号很重要。如果要序列化查询集,则可以将其传入。