根据匹配的字段和图像名称上传图像

时间:2016-09-25 18:05:12

标签: django

我正在构建一个库存清单,其中包含我的 Django 模型中列出的字段。我有一个充满图像的文件夹,图像名称对应Item Number。如需安装,项目编号可能 4119 ,则图片文件名将为 4119.jpg

我想编写一个迭代数据库中的项目并上传相应图像的脚本。任何关于从哪里开始的想法都非常感谢。

from django.db import models

def directory_path(instance, filename):
    return '{0}/{1}/{2}'.format(supplier.name, pricelist.item_number, filename)

class Supplier(models.Model):
    name = models.CharField(max_length=80)

    def __str__(self):
        return self.name

class PriceList(models.Model):
    supplier = models.ForeignKey('Supplier', on_delete=models.CASCADE)
    item_number = models.CharField(max_length=80)
    description = models.CharField(max_length=120)
    case_quantity = models.CharField(max_length=80)
    piece_list_amount = models.CharField(max_length=80)
    partner_list_amount = models.CharField(max_length=80)
    upload = models.ImageField(upload_to=directory_path)


    def __str__(self):
        return self.item_number

1 个答案:

答案 0 :(得分:0)

您可以查看我的代码并准确实现您的需求......我希望这对您有所帮助:

import os
from Project.settings import BASE_DIR
from apps.showcase.models import Product
from django.core.files import File

obj_id_to_img_filename_mapping = (
    (175, 'full_ef58c1a5af252d4459055481b1bbfa76.jpg'),
    (176, 'full_2111856a6a092a3c65639aff56070aef.jpg'),
    (177, 'full_b8154e9b348561ee295c2d1651ecca3c.gif'),
    # ...
)


def update_product_images():
    print('Starting upload products images...\n')
    for product_id, file_name in obj_id_to_img_filename_mapping:
        if file_name:
            product = Product.objects.get(pk=product_id)

            absolute_filename = os.path.join(BASE_DIR, 'apps/showcase/static/showcase/images/initial_data/product', file_name)
            local_file = open(absolute_filename, 'r')
            django_file = File(local_file)

            product.image.save(file_name, django_file, save=True)

            print(absolute_filename + '\n')