如何在django中更改链接upload_to imagefield

t30tvxxf  于 2023-08-08  发布在  Go
关注(0)|答案(2)|浏览(90)

在我的产品模型中有一个类别字段,它指的是另一个表,在类别表中有一个标题字段,我希望每个图像保存在一个文件夹中,名称对应的类别__title

class ProductImage(models.Model):
    title = models.CharField(max_length=100)
    image = models.ImageField(upload_to='...')
    product = models.ForeignKey(Product, on_delete=models.CASCADE)

class Product(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

class Category(models.Model):
    title = models.CharField(max_length=150, verbose_name='title', unique=True)

字符串

k4aesqcs

k4aesqcs1#

我们可以使用upload_to:https://docs.djangoproject.com/en/4.2/ref/models/fields/#django.db.models.FileField.upload_to
paths.py

def upload_product_image(instance, filename):
    # instance is ProductImage object
    # here whatever we want.
    return f"{instance.product.category.title}/{filename}"

字符串
models.py

from .paths import upload_product_image

class ProductImage(models.Model):
    image = models.ImageField(upload_to=upload_product_image)

flvtvl50

flvtvl502#

import os

def image_upload_path(instance, filename):
    # Get the category title for the current product image
    category_title = instance.product.category.title
    # Join the category title with the filename to create the final path
    upload_path = os.path.join('product_images', category_title, filename)
    return upload_path

class ProductImage(models.Model):
    title = models.CharField(max_length=100)
    image = models.ImageField(upload_to=image_upload_path)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)

字符串

相关问题