0

昨天正在解决将图片从 URL 导入到 Django 模型的问题。能够提出一个可行的解决方案,但仍然不知道这是如何工作的。func如何save知道它可以处理什么样的 *args 以及以什么顺序?因为当我更改图片对象和文件名的位置时,它不起作用TypeError: join() argument must be str or bytes, not 'File'。阅读文档无法理解它 - https://docs.djangoproject.com/en/2.1/_modules/django/db/models/base/#Model.save。下面的脚本将 NHL 球员的姓名、ID 和个人资料照片放到我的 Player 模型中。有什么帮助吗?

命令文件:

import urllib.request as urllib
import requests

from django.core.management.base import BaseCommand, CommandError
from django.core.files import File

from players.models import Player


URL_PLAYERS = 'http://www.nhl.com/stats/rest/{}'
URL_PICS = 'https://nhl.bamcontent.com/images/headshots/current/168x168/{}.jpg'


class Command(BaseCommand):

    def import_player(self, data):
        id_ = data["playerId"]
        content = urllib.urlretrieve(URL_PICS.format(id_))
        pic = File(open(content[0], 'rb'))  # do I need to close the file here?
        file = f'{data["playerName"]}.jpg'
        player = Player(name=data["playerName"], nhl_id=id_)
        player.save()
        player.image.save(file, pic)


    def handle(self, *args, **options):

        params = {"isAggregate": "false",
                  "reportType": "basic",
                  "isGame": "false",
                  "reportName": "skaterpercentages",
                  "cayenneExp": "gameTypeId=2 and seasonId=20182019"}

        response = requests.get(url=URL_PLAYERS.format("skaters"),
                                params=params)

        response.raise_for_status()
        data = response.json()["data"]

        for player in data:
            self.import_player(player)

模型文件:

from django.db import models

class Player(models.Model):
    name = models.CharField(max_length=128)
    nhl_id = models.IntegerField()  #(unique=True)
    image = models.ImageField(default='default.jpg', upload_to='players_pics')

    def __str__(self):
        return f'{self.name}'
4

1 回答 1

0

只是为了不让这个问题没有答案。正如@Daniel Roseman 建议的那样,我混淆了两种不同的方法。实际上是使用 FileField保存方法,但以为我使用的是Model.save 方法。因此,正在查看错误的文档。

于 2019-04-03T08:47:48.517 回答