0

1.I want to save data from database(mysql) to .json file format.

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 is

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) In views.py an addbook function is used to add the related data to database.

2) I have to store the database content to a json file after each entry.

3) Can i get help to code the same.

4

1 回答 1

0

这个链接解释了如何序列化 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] 周围的方括号很重要。如果您正在序列化一个查询集,那么您可以将其传入。

于 2013-04-03T17:31:28.030 回答