Django Order By Empty Value Count

Django Order By Empty Value Count,第1张

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

# Calculate non-empty fields count
class Picture(models.Model):
    picture1 = models.CharField(help_text="picture 1", max_length=255, blank=True)  
    picture2 = models.CharField(help_text="picture 2", max_length=255, blank=True)
    # save it to the database
    non_empty_fields = property(picture_count)

    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  

    class Meta:
        ordering = ('picture_count', '-id')

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/714723.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存