【问题标题】:Django python how do i get multiple images in a modelDjango python如何在模型中获取多个图像
【发布时间】:2020-06-22 18:00:51
【问题描述】:
class Product(models.Model):

    name = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(max_length=255, unique=True)
    price = models.DecimalField(max_digits=9, decimal_places=2)
    quantity = models.IntegerField()
    categories = models.ManyToManyField(Category, related_name='categories')
    image = models.ImageField(default='default.jpg', upload_to='product_images')
    image2 = models.ImageField(default='default.jpg', upload_to='product_images')
    image2 = models.ImageField(default='default.jpg', upload_to='product_images')
    active = models.BooleanField(default=True)
    created_at = models.TimeField(auto_now_add=True)
    updated_at = models.TimeField(auto_now=True)

这是我现在拥有的代码,但现在我无法选择只上传 1 张图片还是 3 张图片。 有没有办法有时只有一个图像域,有时有多个?

【问题讨论】:

标签: python django image model


【解决方案1】:

我认为最好的方法是使用一对多关系,定义一个 Image 模型并设置对它的父 Product 的引用,如下所示:

class ProductImage(models.Model):

    # callable for image upload path
    def whereToUpload(instance, filename):
        return "Product/" + instance.place.name

    image = models.ImageField(upload_to=whereToUpload)
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="productimage")

并从您的产品模型中删除图像字段,然后为了获取特定产品的图像,您可以使用如下 ORM:

product_ID = 5
images = ProductImage.objects.filter(product_id = product_ID)

图片将成为您的产品图片路径

【讨论】:

    猜你喜欢
    • 2018-11-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 2015-10-20
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多