Reputation: 441
I have the folllowing class model in my Django website:
class Buy(models.Model):
category = models.ForeignKey(Category, related_name='sell', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
image = models.FileField()
image2 = models.FileField(blank=True)
description = models.CharField(max_length=300)
date = models.DateField(default=timezone.now)
buy_price = models.DecimalField(max_digits=6, decimal_places=2)
sell_price = models.DecimalField(max_digits=6, decimal_places=2)
seller = models.ForeignKey(Seller, on_delete=models.PROTECT)
showcase = models.BooleanField(default=False)
As you can see, I store photos files with 2 fields: image and image2. But now my client requested me to add more photos. My doubt is:
What is the best practice?
Thank you!
Upvotes: 0
Views: 396
Reputation: 896
On #1, the best practice is to follow database normalization principles, and create a separate Image
model that relates back to your Buy
model. If you anticipate that the images may be reused in several Buy
model instances, use many-to-many relationships; otherwise, use many-to-one (i.e. ForeignKey
). That means removing image
and image2
from your Buy
model, and then creating e.g.:
class Image(models.Model):
image = models.FileField()
image_type = models.CharField()
buy = models.ForeignKey(Buy, on_delete=models.PROTECT)
By #2, if you mean you're considering skipping using FileField
or ImageField
to instead write code that will search for files in some storage space, then that doesn't sound like a good idea, because then you're divorcing your file (meta)data from the rest of your database contents. Using FiledField
/ImageField
will also make it much easier to use storage backends such as AWS S3.
Upvotes: 2