简体   繁体   中英

Count # of non-empty fields in Django

I'm trying to make a site where people can create an event, then add pictures (from an outside album, no need to upload), and then I want to pull info about how many pictures are added and display that on a central catalog. For example (excluding some code for brevity's sake):

models.py

class EventDB(models.Model):
     picture1 = models.CharField ("picture 1", max_length=255, blank=True)
     picture2 = models.CharField ("picture 2", max_length=255, blank=True)

If someone added an item to EventDB and added 1 picture, I could return the output as 1. If they added 2 pictures, it would return as 2, and so on and so forth.

I want to have a central page that lists all the events and has the corresponding number of pictures next to it. For example:

Event1 (2)

Event2 (1)

Event3 (4)

where the number in parenthesis is the # of pictures. What would be the best way to do this? I've tried playing around with (picture1__isnull=True).count() but that counts the TOTAL number of items in my DB without a picture1 uploaded.

Thanks!!

Add a property or a function that will count the total number of pictures for you:

class EventDB(models.Model):
    picture1 = models.CharField ("picture 1", max_length=255, blank=True)  
    picture2 = models.CharField ("picture 2", max_length=255, blank=True)

    def picture_count(self):
        fields = self._meta.get_fields()
        n_count = len([ x for x in fields if getattr(self, field.name) ])
        return n_count    

Alternatively you can write an F function that will do the annotation for you in the database. The syntax of the function will vary based on your database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM