如何使用Django命令为db提供外部API?

2024-09-30 22:20:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习django,我想用https://pokeapi.coAPI为我的django数据库提供支持,这样我就可以在HTML上创建一个下拉列表,列出最新的每个口袋妖怪名称

fetchnames.py

import requests as r


def nameslist():
    payload = {'limit':809}
    listpokemons = []
    response = r.get('https://pokeapi.co/api/v2/pokemon', params=payload)
    pokemons = response.json()
    for line in pokemons['results']:
        listpokemons.append(line['name'])
    return listpokemons

### Function that request from API and returns a list of pokemon names (['Bulbassaur', 'Ivyssaur',...)

核心应用程序/management/commands/queryapi.py

from core_app.models import TablePokemonNames
from core_app.fetchnames import nameslist


class FetchApi(BaseCommand):
    help = "Update DB with https://pokeapi.co/"

    def add_model_value(self):
        table = TablePokemonNames()
        table.names = nameslist()
        table.save()

core_app/models.py

class TablePokemonNames(models.Model):
    id = models.AutoField(primary_key=True)
    names = models.CharField(max_length=100)

我很确定我错过了很多东西,因为我还在学习使用django,我仍然对如何使用django命令感到困惑,但是,我尝试使用nameslist()函数来生成django命令,但数据库没有发生任何事情,使用列表为数据库提供数据有什么问题吗


Tags: djangofrompyhttpscoreimport数据库app