[英]Trouble understanding how the Django save() handles *args
昨天在與將圖片從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和個人資料照片添加到我的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}'
只是為了不讓問題懸而未決。 正如@Daniel Roseman建議的那樣,我混淆了兩種不同的方法。 實際上使用的是FileField save方法 ,但以為我使用的是Model.save方法 。 因此,正在查看錯誤的文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.