下面引用来自Django的官方文档
https://docs.djangoproject.com/zh-hans/3.0/topics/files/
在模型中使用文件¶
当您使用FileField
或ImageField
时,Django提供了一组处理文件的API。
考虑下面的模型,使用ImageField
来存储照片:
from django.db import models
class Car(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=5, decimal_places=2)
photo = models.ImageField(upload_to='cars')
任何Car
实例将拥有一个photo
属性,你可以使用它来获取附加照片的详情:
>>> car = Car.objects.get(name="57 Chevy")
>>> car.photo
<ImageFieldFile: cars/chevy.jpg>
>>> car.photo.name
'cars/chevy.jpg'
>>> car.photo.path
'/media/cars/chevy.jpg'
>>> car.photo.url
'http://media.example.com/cars/chevy.jpg'
car.photo
是一个File
对象,这意味着它拥有以下所描述的所有方法和属性。
注解
文件在数据库中作为保存模型的一部分,因此在模型被保存之前,不能依赖磁盘上使用的实际文件名。
例如,您可以通过将文件名设置为相对于文件存储位置的路径来更改文件名(如果您正在使用FileSystemStorage
替换的,则为MEDIA_ROOT
)。
>>> import os
>>> from django.conf import settings
>>> initial_path = car.photo.path
>>> car.photo.name = 'cars/chevy_ii.jpg'
>>> new_path = settings.MEDIA_ROOT + car.photo.name
>>> # Move the file on the filesystem
>>> os.rename(initial_path, new_path)
>>> car.save()
>>> car.photo.path
'/media/cars/chevy_ii.jpg'
>>> car.photo.path == new_path
True
注解
虽然ImageField
无图像数据属性,比如height
,width
和size
在实例上可用,但不重新打开图片的时候,无法使用底层图像数据比如:
>>> from PIL import Image
>>> car = Car.objects.get(name='57 Chevy')
>>> car.photo.width
191
>>> car.photo.height
287
>>> image = Image.open(car.photo)
# Raises ValueError: seek of closed file.
>>> car.photo.open()
<ImageFieldFile: cars/chevy.jpg>
>>> image = Image.open(car.photo)
>>> image
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=191x287 at 0x7F99A94E9048>