Django自定义Field(青铜版)

2018-04-01  本文已影响0人  青铜搬砖工

当Django提供的Field无法满足我们的需求时,可以通过自定义Field来解决这个问题。
每个自定义的Field,都需要继承django.db.models.Field,

CustomField.py文件

from  django.db.models.fields import Field,CharField
from  django.contrib.auth.hashers import make_password,check_password
from django.utils import six


class SmallIntegerField(Field):
    db_field = 'smallint'


class PasswordFieldCustom(Field):
 
    def  from_db_value(self, value,expression, connection,context):
       return value

    def to_python(self, value):
               return value

    def get_prep_value(self, value):
        if isinstance(value, six.string_types) or value is None:
            return make_password(value, None, 'pbkdf2_sha256')
        return '55555'


models.py文件

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .CustomFields import  TimeStampField,SmallIntegerField,PasswordFieldCustom
from django.db import models

# Create your models here.


class TestModel(models.Model):
    # timestamp = TimeStampField()
    userid = SmallIntegerField()
    password = PasswordFieldCustom(default='12333333',max_length=1000)

    class Meta():
        verbose_name ='test'
        verbose_name_plural =verbose_name;

数据库中创建出来的表

image.png

testModel.py

import os,django
from  django.contrib.auth.hashers import make_password,check_password
from users.models import TestModel
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CustomFieldTest.settings")# project_name 项目名称
django.setup()

user =TestModel()
user.userid =1238;
user.password ='1'
user.save()
user1 =  TestModel.objects.get(userid='1238')
check_password('1',user1.password)
print(check_password('1',user1.password))

数据库数据

image.png
上一篇下一篇

猜你喜欢

热点阅读