在我的Django项目中,我想从目录中上传产品的批量图像。每个目录都以产品的SKU命名。每个目录中可能有也可能没有多个图像。如何实现此功能?
我的模型:
class Product(models.Model):
sku = models.CharField('SKU', max_length = 200)
name = models.CharField('Name', max_length = 1000)
price = models.CharField('Price', max_length = 200)
quantity = models.CharField('Quantity', max_length = 200)
class Meta:
verbose_name = 'Product'
verbose_name_plural = 'Products'
def __str__(self):
return self.name
class Image(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='product_image')
image = models.ImageField(upload_to='images/')
class Meta:
verbose_name = 'Image'
verbose_name_plural = 'Images'
def __str__(self):
return str(self.image)
我的urls.py
from django.urls import path
from . import views
urlpatterns = [
path('products/', views.products, name="products"),
path('products_import/', views.products_import, name="products_import"),
]
我的views.py
def products_import(request):
heading = 'Upload Products'
info = '''This importer will import the following fields: sku, name, price, quantity from a csv file.'''
if request.method == 'POST':
paramFile = io.TextIOWrapper(request.FILES['file'].file, encoding='latin-1')
product = csv.DictReader(paramFile)
list_of_dict = list(product)
objs = [
Product(
sku=row['sku'],
name=row['name'],
price=row['price'],
quantity=row['quantity'],
)
for row in list_of_dict
]
record_count = len(list_of_dict)
try:
msg = Product.objects.bulk_create(objs)
messages.success(request, str(record_count) + ' records were uploaded.')
return redirect('products_import')
except Exception as e:
error_message = 'Error While Importing Data: ',e
messages.error(request, error_message, e)
return redirect('products_import')
context = {'heading': heading, 'info': info}
return render(request, 'coreapp/product/products_import.html', context)
我可以使用下面的CSV和上面的视图上传批量产品。
下面的每个SKU文件夹中都有多个图像。
我想立即上传文件夹中的图像,并将它们与各自的SKU链接。我怎样才能做到这一点?任何指导都将不胜感激。
注:我可以上传一个产品的单一图像。如果我们想上传成千上万的产品及其相关图片,上传一张图片并不是一个可行的解决方案。
复制
使用自定义命令代替视图。在这种情况下,它将更加有用和舒适。这里有一个链接如何做到这一点。
命令的主要部分看起来像这样。
import os
from django.conf.settings import MEDIA_ROOT
...
for data in products_data:
product = Product.objects.create(sku=data['sku'], ...)
images = os.listdir(os.path.join(MEDIA_ROOT, 'images'))
for image in images:
Image.objects.create(
product=product,
image=f'images/{product.sku}/image'
)
确保图像目录下没有任何文件,除了图像。