zoukankan      html  css  js  c++  java
  • Django自定义--model字段

    自定义字段

    • model字段就是在处理python对象/数据库值/查询值之间的转换
    • to_python() 被下面的代替,兼容考虑也要使用
    • from_db_value() 从数据库加载数据转为python对象
    • get_prep_value() 将python对象转为查询值
    • get_db_prep_value() 将查询值转为数据库值
    • pre_save() 保存前预处理
    • get_prep_lookup() 准备用于数据库查找的值
    • 通常定义前3个方法

    下面是比较特殊的图片字段

    def _add_thumb(s):
            parts = s.split(".")
            parts.insert(-1, 'thumb')
            if parts[-1].lower() not in ['jpeg', 'jpg']:
                parts[-1] = 'jpg'
            return '.'.join(parts)
    
        class ThumbnailImageFieldFile(ImageFieldFile):
                def _get_thumb_path(self):
                   return _add_thumb(self.path)
                thumb_path = property(_get_thumb_path)
    
            def _get_thumb_url(self):
                return _add_thumb(self.url)
            thumb_url = property(_get_thumb_url)
           
            def save(self, name, content, save=True):
                super(ThumbnailImageFieldFile, self).save(name, content, save)
                img = Image.open(self.path)
                img.thumbnail(
                    (self.field.thumb_width, self.field.thumb_height),
                    Image.ANTIALIAS
                )
                img.save(self.thumb_path, "JPEG")
    
            def delete(self, save=True):
               if os.path.exists(self.thumb_path):
                    os.remove(self.thumb_path)
                super(ThumbnailImageFieldFile, self).delete(save)
    
    class ThumbnailImageField(ImageField):
    
        attr_class = ThumbnailImageFieldFile
    
        def __init__(self, thumb_width=128, thumb_height=128, *args, **kwargs):
            self.thumb_width = thumb_width
            self.thumb_height = thumb_height
            super(ThumbnailImageField, self).__init__(*args, **kwargs)
    
  • 相关阅读:
    十五周作业
    第十四周总结
    十三周总结与感想
    排球比赛积分规则
    Centos + nginx + JBOSS AS 7 搭建Java web application
    eclipse + maven + jboss 遇到ClassNotFoundException
    “/”应用程序中的服务器错误。 纠错方法
    Sharepoint 问题集锦
    Sharepoint 问题集锦
    Sharepoint 问题集锦
  • 原文地址:https://www.cnblogs.com/wj5633/p/7083171.html
Copyright © 2011-2022 走看看