Create javascript object (class) from django model

2019-06-27 15:54发布

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?

1条回答
戒情不戒烟
2楼-- · 2019-06-27 16:32

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 }} ;
查看更多
登录 后发表回答