Django 프레임워크 전체 설명 - 모델

49425 단어 Django
Django는 웹 응용 프로그램의 데이터를 구축하고 관리하기 위한 추상적인 레이어("Model")를 제공합니다.django에서는 코드에 정의된 클래스에 따라 데이터베이스 테이블을 자동으로 생성하는 Code Frist 원칙을 따릅니다.관계 객체 매핑(Object Relational Mapping, ORM)1. 표 a, 기본 구조 만들기
from django.db import models

 class userinfo(models.Model):
    name = models.CharField(max_length=30)
    email = models.EmailField()
    memo = models.TextField()
1、null=True
              
2、blank=True
  django  Admin              
3、primary_key = False
    , AutoField     ,          id  
4、auto_now   auto_now_add
  auto_now       ---       ,         
  auto_now_add      ---         
5、choices
GENDER_CHOICE = (
        (u'M', u'Male'),
        (u'F', u'Female'),
    )
gender = models.CharField(max_length=2,choices = GENDER_CHOICE)
6、max_length
7、default     
8、verbose_name  Admin        
9、name|db_column           
10、unique=True       
11、db_index = True       
12、editable=True   Admin      
13、error_messages=None      
14、auto_created=False      
15、help_text   Admin       
16、validators=[]
17、upload-to
1、models.AutoField      = int(11)
        ,           id   ,              ,           primary_key=True2、models.CharField       
     max_length   
3、models.BooleanField      =tinyint(1)
      ,Blank=True
4、models.ComaSeparatedIntegerField          =varchar
    CharField,     max_lenght   
5、models.DateField       date
      ,auto_now = True              ;auto_now_add           ,         。
6、models.DateTimeField       datetime
   DateField   
7、models.Decimal          = decimal
         max_digits    decimal_places
8、models.EmailField       (       ) =varchar
             
9、models.FloatField       = double
10、models.IntegerField    
11、models.BigIntegerField     
  integer_field_ranges = {
    'SmallIntegerField': (-32768, 32767),
    'IntegerField': (-2147483648, 2147483647),
    'BigIntegerField': (-9223372036854775808, 9223372036854775807),
    'PositiveSmallIntegerField': (0, 32767),
    'PositiveIntegerField': (0, 2147483647),
  }
12、models.IPAddressField       (ip4     )
13、models.GenericIPAddressField       (ip4 ip6    )
    protocol   :both、ipv4、ipv6
     ,       
14、models.NullBooleanField           
15、models.PositiveIntegerFiel   Integer
16、models.PositiveSmallIntegerField   smallInteger
17、models.SlugField    、   、  、  
18、models.SmallIntegerField    
          :tinyint、smallint、int、bigint
19、models.TextField     =longtext
20、models.TimeField     HH:MM[:ss[.uuuuuu]]
21、models.URLField     ,       
22、models.BinaryField     
23、models.ImageField     
24、models.FilePathField   
class UserInfo(models.Model):
        nid = models.AutoField(primary_key=True)
        username = models.CharField(max_length=32)
        class Meta:
            #               app   +     +   
            db_table = "table_name"

            #     
            index_together = [
                ("pub_date", "deadline"),
            ]

            #       
            unique_together = (("driver", "restaurant"),)

            # admin       
            verbose_name

            # verbose_name s
            verbose_name_plural

      :https://docs.djangoproject.com/en/1.10/ref/models/options/
1.  Model              :
        a. Django Admin           Admiin   ModelForm      ,     ,    Model            
        b.   Model    clean_fields   , :
            # models.py
            class UserInfo(models.Model):
                nid = models.AutoField(primary_key=True)
                username = models.CharField(max_length=32)

                email = models.EmailField(error_messages={'invalid': '    .'})

            # views.py
            def index(request):
                obj = models.UserInfo(username='11234', email='uu')
                try:
                    print(obj.clean_fields())
                except Exception as e:
                    print(e)
                return HttpResponse('ok')

           # Model clean       ,       , :       。

    2.Admin       
        # admin.py
        from django.contrib import admin
        from model_club import models
        from django import forms


        class UserInfoForm(forms.ModelForm):
            username = forms.CharField(error_messages={'required': '       .'})
            email = forms.EmailField(error_messages={'invalid': '      .'})
            age = forms.IntegerField(initial=1, error_messages={'required': '     .', 'invalid': '       .'})

            class Meta:
                model = models.UserInfo
                # fields = ('username',)
                fields = "__all__"


        class UserInfoAdmin(admin.ModelAdmin):
            form = UserInfoForm


        admin.site.register(models.UserInfo, UserInfoAdmin)

b. 연표 구조
   :models.ForeignKey(   )
   :models.ManyToManyField(   )
   :models.OneToOneField(   )

    :

       :            ,         (       )
      :        ,          【    】【    】【    】 。
       :           ,           
      :      ,           
       :           ,         (                
      :   10             ,        ,10       ,          5   
ForeignKey(ForeignObject) # ForeignObject(RelatedField)
to,                         #         
to_field=None,              #            
on_delete=None,             #            ,            
- models.CASCADE,      ,       
- models.DO_NOTHING,      ,    IntegrityError
- models.PROTECT,      ,    ProtectedError
- models.SET_NULL,      ,         null(  FK         )
- models.SET_DEFAULT,      ,            (  FK         )
- models.SET,      ,
a.             ,  :models.SET( )
b.                   ,  :models.SET(     )

def func():
    return 10

class MyModel(models.Model):
    user = models.ForeignKey(
        to="User",
        to_field="id"
    on_delete=models.SET(func),)
related_name=None,          #      ,      ,     【  _set】  : obj.  _set.all()
related_query_name=None,    #      ,       ,    【  】      : models.UserGroup.objects.filter(  __   =1).values('  __   ')
limit_choices_to=None,      #  Admin ModelForm        ,     :
#  :
- limit_choices_to={'nid__gt': 5}
- limit_choices_to=lambda : {'nid__gt': 5}

from django.db.models import Q
- limit_choices_to=Q(nid__gt=10)
- limit_choices_to=Q(nid=8) | Q(nid__gt=10)
- limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')
db_constraint=True          #              
parent_link=False           #  Admin         


OneToOneField(ForeignKey)
to,                         #         
to_field=None               #            
on_delete=None,             #            ,            

######       ######
# 1.             +     
# 2.            ,            
#     A        c_ptr_id    :
class C(models.Model):
    nid = models.AutoField(primary_key=True)
    part = models.CharField(max_length=12)

class A(C):
    id = models.AutoField(primary_key=True)
    code = models.CharField(max_length=1)

ManyToManyField(RelatedField)
to,                         #         
related_name=None,          #      ,      ,     【  _set】  : obj.  _set.all()
related_query_name=None,    #      ,       ,    【  】      : models.UserGroup.objects.filter(  __   =1).values('  __   ')
limit_choices_to=None,      #  Admin ModelForm        ,     :
#  :
- limit_choices_to={'nid__gt': 5}
- limit_choices_to=lambda : {'nid__gt': 5}

from django.db.models import Q
- limit_choices_to=Q(nid__gt=10)
- limit_choices_to=Q(nid=8) | Q(nid__gt=10)
- limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')
symmetrical=None,           #           ,symmetrical                 
#       ,   symmetrical         
models.BB.objects.filter(...)

#      :code, id, m1
class BB(models.Model):

code = models.CharField(max_length=12)
m1 = models.ManyToManyField('self',symmetrical=True)

#      : bb, code, id, m1
class BB(models.Model):

code = models.CharField(max_length=12)
m1 = models.ManyToManyField('self',symmetrical=False)

through=None,               #         ,           
through_fields=None,        #         ,                       
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=50)

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(
        Person,
        through='Membership',
        through_fields=('group', 'person'),
    )

class Membership(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    inviter = models.ForeignKey(
        Person,
        on_delete=models.CASCADE,
        related_name="membership_invites",
    )
    invite_reason = models.CharField(max_length=64)
db_constraint=True,         #              
db_table=None,              #          ,        

2. 조작표 a, 기본 조작
    #  
    #
    # models.Tb1.objects.create(c1='xx', c2='oo')        ,           **kwargs

    # obj = models.Tb1(c1='xx', c2='oo')
    # obj.save()

    #  
    #
    # models.Tb1.objects.get(id=123)         #       ,      (   )
    # models.Tb1.objects.all()               #     
    # models.Tb1.objects.filter(name='seven') #          

    #  
    #
    # models.Tb1.objects.filter(name='seven').delete() #          

    #  
    # models.Tb1.objects.filter(name='seven').update(gender='0')  #           ,    **kwargs
    # obj = models.Tb1.objects.get(id=1)
    # obj.c1 = '111'
    # obj.save()                                                 #       

b. 진급 작업(일어나지 않는 쌍밑줄)을 쌍밑줄로 필드와 대응하는 조작을 연결한다.
        #     
        #
        # models.Tb1.objects.filter(name='seven').count()

        #   ,  
        #
        # models.Tb1.objects.filter(id__gt=1)              #   id  1  
        # models.Tb1.objects.filter(id__gte=1)              #   id    1  
        # models.Tb1.objects.filter(id__lt=10)             #   id  10  
        # models.Tb1.objects.filter(id__lte=10)             #   id  10  
        # models.Tb1.objects.filter(id__lt=10, id__gt=1)   #   id  1     10  

        # in
        #
        # models.Tb1.objects.filter(id__in=[11, 22, 33])   #   id  112233   
        # models.Tb1.objects.exclude(id__in=[11, 22, 33])  # not in

        # isnull
        # Entry.objects.filter(pub_date__isnull=True)

        # contains
        #
        # models.Tb1.objects.filter(name__contains="ven")
        # models.Tb1.objects.filter(name__icontains="ven") # icontains      
        # models.Tb1.objects.exclude(name__icontains="ven")

        # range
        #
        # models.Tb1.objects.filter(id__range=[1, 2])   #   bettwen and

        #     
        #
        # startswith,istartswith, endswith, iendswith,

        # order by
        #
        # models.Tb1.objects.filter(name='seven').order_by('id')    # asc
        # models.Tb1.objects.filter(name='seven').order_by('-id')   # desc

        # group by
        #
        # from django.db.models import Count, Min, Max, Sum
        # models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))
        # SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"

        # limit 、offset
        #
        # models.Tb1.objects.all()[10:20]

        # regex    ,iregex       
        #
        # Entry.objects.get(title__regex=r'^(An?|The) +')
        # Entry.objects.get(title__iregex=r'^(an?|the) +')

        # date
        #
        # Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
        # Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))

        # year
        #
        # Entry.objects.filter(pub_date__year=2005)
        # Entry.objects.filter(pub_date__year__gte=2005)

        # month
        #
        # Entry.objects.filter(pub_date__month=12)
        # Entry.objects.filter(pub_date__month__gte=6)

        # day
        #
        # Entry.objects.filter(pub_date__day=3)
        # Entry.objects.filter(pub_date__day__gte=3)

        # week_day
        #
        # Entry.objects.filter(pub_date__week_day=2)
        # Entry.objects.filter(pub_date__week_day__gte=2)

        # hour
        #
        # Event.objects.filter(timestamp__hour=23)
        # Event.objects.filter(time__hour=5)
        # Event.objects.filter(timestamp__hour__gte=12)

        # minute
        #
        # Event.objects.filter(timestamp__minute=29)
        # Event.objects.filter(time__minute=46)
        # Event.objects.filter(timestamp__minute__gte=29)

        # second
        #
        # Event.objects.filter(timestamp__second=31)
        # Event.objects.filter(time__second=2)
        # Event.objects.filter(timestamp__second__gte=31)

c. 기타 조작
    # extra
    #
    # extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
    #    Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))
    #    Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
    #    Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
    #    Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'])

    # F
    #
    # from django.db.models import F
    # models.Tb1.objects.update(num=F('num')+1)


    # Q
    #
    # # Q(nid__gt=10)
    # Q(nid=8) | Q(nid__gt=10)
    # Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')
    # # con = Q()
    # q1 = Q()
    # q1.connector = 'OR'
    # q1.children.append(('id', 1))
    # q1.children.append(('id', 10))
    # q1.children.append(('id', 9))
    # q2 = Q()
    # q2.connector = 'OR'
    # q2.children.append(('c1', 1))
    # q2.children.append(('c1', 10))
    # q2.children.append(('c1', 9))
    # con.add(q1, 'AND')
    # con.add(q2, 'AND')
    #
    # models.Tb1.objects.filter(con)


    #     SQL
    #
    # from django.db import connection, connections
    # cursor = connection.cursor()  # cursor = connections['default'].cursor()
    # cursor.execute("""SELECT * from auth_user where id = %s""", [1])
    # row = cursor.fetchone()

d. 테이블 연결 작업(일어나지 않는 이중 밑줄)은 이중 밑줄과 를 이용한다.set 테이블 사이의 조작을 연결합니다
#      
class UserProfile(models.Model):
    user_info = models.OneToOneField('UserInfo')
    username = models.CharField(max_length=64)
    password = models.CharField(max_length=64)

    def __unicode__(self):
        return self.username


class UserInfo(models.Model):
    user_type_choice = (
        (0, u'    '),
        (1, u'    '),
    )
    user_type = models.IntegerField(choices=user_type_choice)
    name = models.CharField(max_length=32)
    email = models.CharField(max_length=32)
    address = models.CharField(max_length=128)

    def __unicode__(self):
        return self.name


class UserGroup(models.Model):

    caption = models.CharField(max_length=64)

    user_info = models.ManyToManyField('UserInfo')

    def __unicode__(self):
        return self.caption


class Host(models.Model):
    hostname = models.CharField(max_length=64)
    ip = models.GenericIPAddressField()
    user_group = models.ForeignKey('UserGroup')

    def __unicode__(self):
        return self.hostname
  #      
user_info_obj = models.UserInfo.objects.filter(id=1).first()
print user_info_obj.user_type
print user_info_obj.get_user_type_display()
print user_info_obj.userprofile.password

user_info_obj = models.UserInfo.objects.filter(id=1).values('email', 'userprofile__username').first()
print user_info_obj.keys()
print user_info_obj.values()
 #    
 #      
    dic = {
        "hostname": "  1",
        "ip": "192.168.1.1",
        "user_group_id": 1,   #      "user_group"
    }
    models.Host.objects.create(**dic)

    #       
    host_obj = models.Host.objects.all()
    print(type(host_obj),     # 'django.db.models.query.QuerySet'>
          host_obj)           # 1>]>
    for item in host_obj:
        print(item.hostname)
        print(item.user_group.caption)
        print(item.user_group.user_info.values())
        # 'name': 'nick', 'user_type': 1, 'id': 1, 'email': '[email protected]', 'address': '128 '}]>

    usergroup_obj = models.Host.objects.filter(user_group__caption='  1')
    print(usergroup_obj)


    #       
    usergroup_obj = models.UserGroup.objects.get(id=1)
    print(usergroup_obj.caption)
    ret = usergroup_obj.host_set.all()  #     id=1 host
    print(ret)

    obj = models.UserGroup.objects.filter(host__ip='192.168.1.1').\
        values('host__id', 'host__hostname')
    print(obj)      # 'host__id': 1, 'host__hostname': '  1'}]>

 #    
user_info_obj = models.UserInfo.objects.get(name='nick')
user_info_objs = models.UserInfo.objects.all()

group_obj = models.UserGroup.objects.get(caption='CTO')
group_objs = models.UserGroup.objects.all()

#     
#group_obj.user_info.add(user_info_obj)
#group_obj.user_info.add(*user_info_objs)

#     
#group_obj.user_info.remove(user_info_obj)
#group_obj.user_info.remove(*user_info_objs)

#     
#user_info_obj.usergroup_set.add(group_obj)
#user_info_obj.usergroup_set.add(*group_objs)

#     
#user_info_obj.usergroup_set.remove(group_obj)
#user_info_obj.usergroup_set.remove(*group_objs)

#     
#print group_obj.user_info.all()
#print group_obj.user_info.all().filter(id=1)

#     
#print user_info_obj.usergroup_set.all()
#print user_info_obj.usergroup_set.all().filter(caption='CTO')
#print user_info_obj.usergroup_set.all().filter(caption='DBA')

#      
# userinfo_id_1 = models.UserInfo.objects.filter(id=1)
# usergroup_id_1 = models.UserGroup.objects.filter(id=1).first()
# usergroup_id_1.user_info.add(*userinfo_id_1)

확장:a, 사용자 지정 업로드
def upload_file(request):
    if request.method == "POST":
        obj = request.FILES.get('fafafa')
        f = open(obj.name, 'wb')
        for chunk in obj.chunks():
            f.write(chunk)
        f.close()
    return render(request, 'file.html')

b. Form 업로드 파일 인스턴스
# HTML

       
"post" action="/view1/" enctype="multipart/form-data"> type="file" name="ExcelFile" id="id_ExcelFile" /> type="submit" value=" " />
# Form class FileForm(forms.Form): ExcelFile = forms.FileField() # Models from django.db import models class UploadFile(models.Model): userid = models.CharField(max_length = 30) file = models.FileField(upload_to = './upload/') date = models.DateTimeField(auto_now_add=True) # Views def UploadFile(request): uf = AssetForm.FileForm(request.POST,request.FILES) if uf.is_valid(): upload = models.UploadFile() upload.userid = 1 upload.file = uf.cleaned_data['ExcelFile'] upload.save() print upload.file

c.ajax 파일 업로드 실례
 # html
 <div>
       {{ up.ExcelFile }}
       <input type="button" id="submitj" value="  " />
 div>

<script src="/static/js/jquery-2.1.4.min.js">script>
<script>
    $('#submitj').bind("click",function () {
        var file = $('#id_ExcelFile')[0].files[0];
        var form = new FormData();
        form.append('ExcelFile', file);
         $.ajax({
                type:'POST',
                url: '/view1/',
                data: form,
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                success: function(arg){
                    console.log(arg);
                }
            })
    })
script>

 # Form
 class FileForm(forms.Form):
    ExcelFile = forms.FileField()

 # Models
from django.db import models
class UploadFile(models.Model):
    userid = models.CharField(max_length = 30)
    file = models.FileField(upload_to = './upload/')
    date = models.DateTimeField(auto_now_add=True)

 # View
from study1 import forms

def UploadFile(request):
    uf = AssetForm.FileForm(request.POST,request.FILES)
    if uf.is_valid():
            upload = models.UploadFile()
            upload.userid = 1
            upload.file = uf.cleaned_data['ExcelFile']
            upload.save()

            print upload.file

return render(request, 'file.html', locals())

좋은 웹페이지 즐겨찾기