簡體   English   中英

序列化Django模型(用於js文件)?

[英]serializing django models (for use in js files)?

-DJANGO / PYTHON--

class Sounds(models.Model):
    sound = models.TextField(max_length=500, blank=True)
    syl = models.TextField(max_length=500, blank=True)
    tone = models.IntegerField(blank=True, default=0) 

 def as_json(self):
    return dict(
        input_id=self.id, sound=self.sound,
        syl=self.syl, tone=self.tone)

--JS--

function init()
{
    -- create a list of all instances with tone = 1 --
}

這就是我的模型的樣子。 在我的js文件中,我希望能夠將所有創建的具有特定音調(或音節等)的實例放入列表中,以便可以使用它們。 我創建了as_json函數(上面),但是我不確定在哪里調用該函數。 如果我在python文件中調用,那么..如何在js文件中使用它,反之亦然?

您需要提供一個視圖(帶有URL)來調用以獲取Json。 這里有一些例子:

https://simpleisbetterthancomplex.com/tutorial/2016/07/27/how-to-return-json-encoded-response.html

還有更具體的東西:

https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html

為了在此答案中包含一些內容,請考慮以下(偽代碼)視圖:

在“ views.py”中:

from django.http import JsonResponse
from django.template.loader import render_to_string   
from .models import Sounds

def sounds_json_detail(request):
    sound = Sounds.objects.get(some_lookup_here)
    context['sound'] = sound.as_json()
    html_sound = render_to_string('sound_detail.html',
                     context,request=request,
                )
    return JsonResponse({'html_sound': html_sound})

sound_detail.html是您需要提供的模板-我在ajax調用中執行此操作,但是如果您只想發布json,則可以省略此模板。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM