Python Django中非空字段的计数
我正试图建立一个网站,人们可以创建一个活动,然后添加图片(从外部相册,无需上传),然后我想拉多少图片被添加的信息,并显示在一个中央目录。例如(为了简洁起见,排除了一些代码): models.pyPython Django中非空字段的计数,python,django,Python,Django,我正试图建立一个网站,人们可以创建一个活动,然后添加图片(从外部相册,无需上传),然后我想拉多少图片被添加的信息,并显示在一个中央目录。例如(为了简洁起见,排除了一些代码): models.py class EventDB(models.Model): picture1 = models.CharField ("picture 1", max_length=255, blank=True) picture2 = models.CharField ("picture 2", m
class EventDB(models.Model):
picture1 = models.CharField ("picture 1", max_length=255, blank=True)
picture2 = models.CharField ("picture 2", max_length=255, blank=True)
如果有人向EventDB添加了一个项目并添加了一张图片,我可以将输出返回为1。如果他们添加了2张图片,它将返回为2,依此类推
我想有一个中心页面,列出所有的事件,并在旁边有相应数量的图片。例如:
事件1(2)
事件2(1)
事件3(4)
括号中的数字是图片的#。最好的方法是什么?我尝试过使用(picture1\uuu isnull=True).count()进行游戏,但这会计算数据库中没有上传picture1的项目总数
谢谢 添加一个属性或函数,用于计算图片总数:
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
或者,您可以编写一个F
函数,在数据库中为您进行注释。函数的语法会因数据库而异