0
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)

this the code I have now but now I can't choose wether to upload just 1 image or 3. is there a way to have sometimes only one imagefield and sometimes multiple?

  • [This](https://stackoverflow.com/questions/537593/multiple-images-per-model) answer should solve your problem. – Dwij Mehta Jun 22 '20 at 18:20
  • Does this answer your question? [Multiple images per Model](https://stackoverflow.com/questions/537593/multiple-images-per-model) – Ken Kinder Jun 22 '20 at 18:40

1 Answers1

1

i think the best way is using one to many relations, define an Image model and set a reference to it's parent Product like below:

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")

and delete image fields from your Product model,then for fetching images of a specific Product you can use ORM like below:

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

and images will be your Product image path

Ahmad Mansoori
  • 177
  • 1
  • 11