Search code examples
djangomodeldjango-querysetimagefield

Django - count numbers of same field in a model


I'm new to Django and I'm building an e-commerce website (db: sqlite3). Each item on sale has 1-5 images uploaded. So I've got the model here:

class Item(models.Model):
    '''Item model with maximum 5 images uploaded'''

    <--snip-->

    image_1 = models.ImageField(upload_to='items/')
    image_2 = models.ImageField(upload_to='items/', blank=True)
    image_3 = models.ImageField(upload_to='items/', blank=True)
    image_4 = models.ImageField(upload_to='items/', blank=True)
    image_5 = models.ImageField(upload_to='items/', blank=True)

In order to create a carousel (bootstrap4) for each item, I need to know how many images uploaded. My thinking is to create a function in the class to find out how many ImageField there are in this model and how many are not blank.

So my question is:
1. is there a better way to create ImageField, a more dynamic way?
2. is it possible to find out the number of the same field in a model that are not blank?


Solution

  • I would create a separate model for the images and link it to the Item model. This will make filtering easier as well as make image uploads more flexible.

    class ItemImage(models.Model):
        item = models.ForeignKey(Item)
        image = models.ImageField(upload_to='items/')
    
    class Item(models.Model):
        <--snip-->
    
        # we add a model property then do a reverse lookup in order to 
        # count images linked to the item object
        # this can then be accessed by item_obj.image_count
        @property
        def get_image_count(self)
            return self.itemimage_set.all().count()