Felipe Dourado
Felipe Dourado

Reputation: 441

Saving images names into the database - Django

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:

  1. Should I continue adding new fields to this class, for example, image3, image4, image5 and so on? The problem I see: not every records will have so many photos and the most of them will become "empty".
  2. Should I only upload the new photos without saving their names into the database? In this way, the new photos should follow some name related to the image class field. I mean, unique_photo_1.jpg goes inside the image field, unique_photo_2.jpg is not saved into the database but is related to this field, as well as the unique_photo_3.jpg.

What is the best practice?

Thank you!

Upvotes: 0

Views: 396

Answers (1)

DJ Ramones
DJ Ramones

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

Related Questions