JSON data convert to the django model

前端 未结 1 1926
暗喜
暗喜 2020-12-30 14:35

I need to convert JSON data to django model.

This is my JSON data

{
  \"data\": [
    {
      \"id\": \"20ad5d9c-b32e-4599-8866-a3aaa5ac77de\",
              


        
相关标签:
1条回答
  • 2020-12-30 15:02

    Using JSON in Django templates

    You don't have to convert the JSON structure into a Django model just to use it in a Django template: JSON structures (Python dicts) work just fine in a Django template

    e.g. if you pass in {'titles': titles['data']} as the context to your template, you can use it as:

    {% for title in titles %}
        ID is {{title.id}}, and name is {{title.name}}
    {% endfor %}
    

    As long as you don't need to store the data with Django, the above solution works just fine. If you want to store, read below.

    Make a model

    You can create a model to store that JSON data in. Once stored you can pass the queryset to your template

    class Title(models.Model)
        id = models.CharField(max_length=36)
        name = models.CharField(max_length=255)
    

    or use an UUIDField

    class Title(models.Model)
        id = models.UUIDField(primary_key=True)
        name = models.CharField(max_length=255)
    

    Store the data in a Django model

    # Read the JSON
    titles = r.json()
    # Create a Django model object for each object in the JSON 
    for title in titles['data']:
        Title.objects.create(id=title['id'], name=title['name'])
    

    Use stored data to pass as template context

    # Then pass this dict below as the template context
    context = {'titles': Title.objects.all()}
    
    0 讨论(0)
提交回复
热议问题