如何在django模型中保存外部API的键值?

时间:2017-12-04 16:54:33

标签: python django

我的想法是,我想在我的应用中创建一些保存/喜欢按钮。

在我的services.py和views.py中,我调用并显示API数据 API结果看起来像那样

[
    {'rating':4,
     'name': 'Whatever name there is',
     'id': 'whatever ID there is',
    }
]

有没有办法将ID部件保存到我的模型中,我该如何实现?考虑到每次使用api时,API结果都可能会发生变化。

1 个答案:

答案 0 :(得分:0)

您没有指定模型和视图的外观,但我会即兴发挥

models.py

class SomeModel(models.Model):
  extra_id = models.InetgerField()
  raiting = models.IntegerField()
  name = models.TextField()

views.py

from app.models import SomeModel

def save_json(request):
  the_json = {
     'rating':4,
     'name': 'Whatever name there is',
     'id': 'whatever ID there is',
  }

  some_model = SomeModel.objects.create(
    extra_id=int(the_json['id']),
    name=the_json['name'],
    raiting=int(the_json['raiting'])
  )

  # and later if you want make operation on model.
  some_model = SomeModel.objects.get(extra_id=759)
  # for example...
  some_model.raiting = 4 
  some_model.save()