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?

2
  • This answer should solve your problem. Commented Jun 22, 2020 at 18:20
  • Does this answer your question? Multiple images per Model Commented Jun 22, 2020 at 18:40

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.