zoukankan      html  css  js  c++  java
  • django 判断mysql中的bit(1)

    问题:

    django访问mysql数据库时,可以通过自醒的方式获取数据库中的字段。对于mysql中的bit字段,比较特殊,django无法识别, 它将其默认识别为models.TextField?(),这显然是不对的,在将其改为models.BooleanField()后,存储数据正确,数据库里可以查看到数据。 但是在if,else判断时均显示为true,无法进行判别。解决方法很简单,在判断字段时采用ord(field)就行。 看下面的例子就成。



    示例:

    比如在eucalyptus中,eucalyptus_auth数据库中,表auth_users定义如下:

    id varchar(255) NO PRI NULL
    last_update_timestamp datetime YES   NULL
    version int(11) YES   NULL
    auth_user_is_admin bit(1) YES    NULL
    auth_user_is_enabled bit(1)  YES   NULL
    auth_user_name varchar(255) YES UNI NULL
    auth_user_password varchar(255)  YES   NULL
    auth_user_query_id varchar(255) YES   NULL
    auth_user_secretkey  varchar(255) YES   NULL
    auth_user_token varchar(255) YES   NULL


                 
     

     



    其中,字段auth_user_is_admin,auth_user_is_enabled为bit(1)类型,在django通过数据库产生的model中,定义如下:

    class AuthUsers(models.Model):
    id = models.CharField(max_length=765, primary_key=True)
    last_update_timestamp = models.DateTimeField(null=True, blank=True)
    version = models.IntegerField(null=True, blank=True)
    auth_user_is_admin = models.TextField(blank=True) # This field type is a guess
    auth_user_is_enabled = models.TextField(blank=True) # This field type is a guess.
    auth_user_name = models.CharField(unique=True, max_length=765, blank=True)
    auth_user_password = models.CharField(max_length=765, blank=True)
    auth_user_query_id = models.CharField(max_length=765, blank=True)
    auth_user_secretkey = models.CharField(max_length=765, blank=True)
    auth_user_token = models.CharField(max_length=765, blank=True)
    class Meta:
    db_table = u'auth_users'


    django 无法识别mysql中的bit类型,如它的注释:This field type is a guess。在将其更改为 models.BooleanField()后,在检索数据时,无法直接通过if self.auth_user_is_admin进行bool的判断, 无论数据库中auth_user_is_admin是0或是1,if判断均为true,通过添加if ord(self.auth_user_is_admin):来对值进行转换,一切正常了。

  • 相关阅读:
    ChineseAlphabetUtil获取汉字首字母工具类
    RandomCodeUtil随机数工具类,随机生成数字、字母、数字字母组合、中文姓名
    ValidateUtil常用验证工具类,如手机、密码、邮箱等
    聊天项目
    日期
    字符串
    java中属性,set get 以及如何学习类的一些用法
    继承 多态 封装
    方法 属性 构造方法和包
    面向对象知识
  • 原文地址:https://www.cnblogs.com/hanxiangduo/p/django_mysql_bit.html
Copyright © 2011-2022 走看看