How to parse file names (images) and assign them to a model?

Viewed 66

I am relatively new in Django and building an e-commerce application. I have a folder with images (they are in the static directory), and lots of products (~15000, I pull the product data from an API.). Unfortunately I do not pull the image data from the API, instead I have a folder with all the images, and their name contains a fragment of the product.name string.

e.g
product.name = AH 285/55 R16 Turanza AH325
image_path = static/products/images/Turanza__1.png

What I am trying to achieve is the following pseudo code:

if product.name (the string) is contained in the image_name(path of the image), save the image and associate it with the model, otherwise pass.
class Product(models.Model):
    code = models.CharField(primary_key=True, unique=True, max_length=15, null=False, blank=False)
    name = models.CharField(max_length=50, null=True, blank=True)
    brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True, blank=True)
    price = models.FloatField(null=True, blank=True)

    image1 = ...
    image2 = ...

or

class Image(models.Model):
    product = models.ForeignKey(Product, ...)
    name = models.CharField(...)

How would I approach this? Maybe a model property? What is the best practice for a problem like this? Can someone point me in the right direction?

1 Answers

The first thing that comes to me is to pass an extra parameter to the Product model instance when creating it, on this case the filename. Something like this

class Product(models.Model):
    code = models.CharField(primary_key=True, unique=True, max_length=15, null=False, blank=False)
    name = models.CharField(max_length=50, null=True, blank=True)
    brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True, blank=True)
    price = models.FloatField(null=True, blank=True)

    image1 = ...
    image2 = ...

   @classmethod
   def create(cls, filename):
        product = cls(name=filename)
        return product

Then it would work like this:

product = Product.create("filename")

Check out the documentation.

Related