难以理解Django save()如何处理* args

时间:2018-12-21 08:06:39

标签: python django python-3.x django-models django-commands

昨天在与将图片从URL导入Django模型的问题进行斗争。能够提出一个可行的解决方案,但仍然不知道这是如何工作的。 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和个人资料照片添加到我的播放器模型中。有帮助吗?

命令文件:

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}'

1 个答案:

答案 0 :(得分:0)

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