从django模型创建javascript对象

从django模型创建javascript对象

本文介绍了从django模型创建javascript对象(类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个单页应用程序,将从大约十几个不同的django模型加载数据,允许用户操作数据,然后将所有更改保存回数据库。



我可以通过序列化查询集的结果来将django模型传递到模板。例如,我有一个模型Person:

  class Person(models.Model):
id = models.AutoField (primary_key = True)
age = models.IntegerField()
name = models.CharField(max_length = 250)

现在,在我看来,我可以通过序列化将一个person对象传递给json格式的模板

  person_object = serializers.serialize(json,Person.objects.filter(id = 1))


b $ b

然后,在我的javascript:

  var someperson = {{data | safe}}; 

但是,我想在客户端创建一个如果Person是javascript类,而不是简单的json对象:

  var person2 = new Person(id = 5,age = 33m ,name =john); 

我的javascript类是否有继承Django数据模型的方法?或者我需要在django和javascript之间手动重新创建我的数据模型?

解决方案

整个

  person ='new Person(id =%(id)s,age =% ,name =%(name)s)'%
{'id':person_instance.id,....}

然后将其作为上下文变量发送到模板,所以它看起来像这样

  var person2 = {{person}}; 


I am working on an single-page application that will load up data from about a dozen different django models, allow the user to manipulate the data, and then save all changes back to the database.

I can sort of 'pass' the django model to template by serializing a result from a queryset. For example, I have a model Person:

class Person(models.Model):
    id = models.AutoField(primary_key=True)
    age = models.IntegerField()
    name = models.CharField(max_length=250)

Now, in my view, I can pass a "person" object to the template in json format by serializing it

person_object = serializers.serialize("json", Person.objects.filter(id=1))

Then, in my javascript:

var someperson = {{ data|safe }};

However, I would like to be able to create a "new" person on the client side, as if the Person were a javascript class not simply a json object:

var person2 = new Person(id=5,age=33m,name="john");

Is there a way for my javascript "class" to inherit the Django data model? Or do I need to manually re-create my data models between django and javascript?

解决方案

You can put the in a string as a whole

person = 'new Person(id="%(id)s",age="%(age)s",name="%(name)s")' %
 {'id':person_instance.id , ....}

then send it to the template as a context variable , so it look like this

var person2 = {{ person }} ;

这篇关于从django模型创建javascript对象(类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:10