Django에서 모델 필드의 의미, 사용 방법

Model
문서 목록
  • Model
  • 1. 모델 기본 구조
  • 1.필드 이름, 의미
  • 2.매개 변수 의미
  • 3.메타 정보 메타
  • 4.확장
  • 2. 테이블 구조 *****
  • 1.필드 및 매개변수
  • 3. 테이블의 조작(정방향 조회는 필드, 반방향 조회는 테이블 이름)
  • 1.기본 작업(추가, 삭제, 수정, 조사)
  • 2.표 조작 진급(소박의 더블 밑줄)
  • 3.기타
  • 4.테이블 연결 작업(이중 밑줄 사용)
  • 1. ==일대일 운영 ==
  • 2.==일대다 =
  • 3.==다대다==
  • 5.확장(파일 업로드)
  • 6. 대량 삭제
  • 모델 기본 구조
    1. 필드 이름, 의미
    
    AutoField(Field)
        # int   ,       primary_key=True
    
    BigAutoField(AutoField)
        # bigint   ,       primary_key=True
    
         : model        ,           id  
        from django.db import models
    
        class UserInfo(models.Model):
            #          id         
            username = models.CharField(max_length=32)
    
        class Group(models.Model):
            #       
            nid = models.AutoField(primary_key=True)
            name = models.CharField(max_length=32)
    
    SmallIntegerField(IntegerField):
        #     -32768 ~ 32767
    
    PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
        #      0 ~ 32767
    IntegerField(Field)
        #    (    ) -2147483648 ~ 2147483647
    
    PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
        #     0 ~ 2147483647
    
    BigIntegerField(IntegerField):
        #    (    ) -9223372036854775808 ~ 9223372036854775807
    
              
    
        class UnsignedIntegerField(models.IntegerField):
            def db_type(self, connection):
                return 'integer UNSIGNED'
    
        PS:               ,Django       :
            'AutoField': 'integer AUTO_INCREMENT',
            'BigAutoField': 'bigint AUTO_INCREMENT',
            'BinaryField': 'longblob',
            'BooleanField': 'bool',
            'CharField': 'varchar(%(max_length)s)',
            'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
            'DateField': 'date',
            'DateTimeField': 'datetime',
            'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
            'DurationField': 'bigint',
            'FileField': 'varchar(%(max_length)s)',
            'FilePathField': 'varchar(%(max_length)s)',
            'FloatField': 'double precision',
            'IntegerField': 'integer',
            'BigIntegerField': 'bigint',
            'IPAddressField': 'char(15)',
            'GenericIPAddressField': 'char(39)',
            'NullBooleanField': 'bool',
            'OneToOneField': 'integer',
            'PositiveIntegerField': 'integer UNSIGNED',
            'PositiveSmallIntegerField': 'smallint UNSIGNED',
            'SlugField': 'varchar(%(max_length)s)',
            'SmallIntegerField': 'smallint',
            'TextField': 'longtext',
            'TimeField': 'time',
            'UUIDField': 'char(32)',
    
    BooleanField(Field)
        #      
    
    NullBooleanField(Field):
        #         
    
    CharField(Field)
        #     
        #     max_length  , max_length      
    
    TextField(Field)
        #     
    
    EmailField(CharField)#      ,Django Admin  ModelForm       
    
    IPAddressField(Field)
        #      ,Django Admin  ModelForm      IPV4   
    
    GenericIPAddressField(Field)
        #      ,Django Admin  ModelForm      Ipv4 Ipv6
        #   :
            protocol,    Ipv4 Ipv6, 'both',"ipv4","ipv6"
            unpack_ipv4,      True::ffff:192.0.2.1192.0.2.1,     ,  protocol="both"
    
    URLField(CharField)
        #      ,Django Admin  ModelForm      URL
    
    SlugField(CharField)
        #      ,Django Admin  ModelForm          、  、   、   (  )
    
    CommaSeparatedIntegerField(CharField)
        #      ,            
    
    UUIDField(Field)
        #      ,Django Admin  ModelForm    UUID     
    
    FilePathField(Field)
        #    ,Django Admin  ModelForm              
        #   :
                path,                           
                match=None,                    
                recursive=False,                   
                allow_files=True,              
                allow_folders=False,            
    
    FileField(Field)
        #    ,        ,         
        #   :
            upload_to = ""               
            storage = None          ,  django.core.files.storage.FileSystemStorage
    
    ImageField(FileField)
        #    ,        ,         
        #   :
            upload_to = ""               
            storage = None          ,  django.core.files.storage.FileSystemStorage
            width_field=None,                   (   )
            height_field=None                   (   )
    
    DateTimeField(DateField)
        #   +     YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]
    
    DateField(DateTimeCheckMixin, Field)
        #           YYYY-MM-DD
    
    TimeField(DateTimeCheckMixin, Field)
        #           HH:MM[:ss[.uuuuuu]]
    
    DurationField(Field)
        #    ,    ,      bigint  ,ORM      datetime.timedelta  
    
    FloatField(Field)
        #    
    
    DecimalField(Field)
        # 10    
        #   :
            max_digits,     
            decimal_places,     
    
    BinaryField(Field)
        #      
    
      
    
    

    2. 매개변수 의미
    null                            
    db_column                    
    db_tablespace
    default                       
    primary_key                    
    db_index                          
    unique                              
    unique_for_date           【  】            
    unique_for_month          【 】            
    unique_for_year           【 】            
    
    verbose_name        Admin        
    blank               Admin           
    editable            Admin       
    help_text           Admin         
    choices             Admin         ,                    
                         :gf = models.IntegerField(choices=[(0, '  '),(1, '   '),],default=1)
    
    error_messages             (    ),             ;
                           :null, blank, invalid, invalid_choice, unique, and unique_for_date
                         :{'null': "    .", 'invalid': '    '}
    
    validators                 (    ),           
                        from django.core.validators import RegexValidator
                        from django.core.validators import EmailValidator,URLValidator,DecimalValidator,\
                        MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
                         :
                            test = models.CharField(
                                max_length=32,
                                error_messages={
                                    'c1': '     1',
                                    'c2': '     2',
                                    'c3': '     3',
                                },
                                validators=[
                                    RegexValidator(regex='root_\d+', message='   ', code='c1'),
                                    RegexValidator(regex='root_112233\d+', message='    ', code='c2'),
                                    EmailValidator(message='    ', code='c3'), ]
                            )
    
    

    3. 메타 정보 메타(데이터베이스 테이블 이름 작성 등 조작에 관여)
    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/
    

    4. 확장
  • 갈고리 함수, 모델 검증 트리거, 오류 알림
  • form 검증(error messages는 반드시 정의해야 하는 것이 아니라 프레임워크가 가지고 있는 정보도 충분히 판단할 수 있다.)
  • 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)
    
    

    2. 테이블 구조 *****
  • 일대다: 모델스.ForeignKey(기타 테이블)
  • 다대다:models.ManyToManyField(기타 테이블)
  • 일대일:models.OneToOneField(기타 표)
  • 1. 필드 및 매개변수
    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,              #          ,        
    
    
    

    Stack overflow 네티즌의 답변:
    This is the behaviour to adopt when the referenced object is deleted. It is not specific to django, this is an SQL standard.
    There are 6 possible actions to take when such event occurs: CASCADE : When the referenced object is deleted, also delete the objects that have references to it (When you remove a blog post for instance, you might want to delete comments as well). SQL equivalent: CASCADE . PROTECT : Forbid the deletion of the referenced object. To delete it you will have to delete all objects that reference it manually. SQL equivalent: RESTRICT . SET_NULL : Set the reference to NULL (requires the field to be nullable). For instance, when you delete a User, you might want to keep the comments he posted on blog posts, but say it was posted by an anonymous (or deleted) user. SQL equivalent: SET NULL . SET_DEFAULT : Set the default value. SQL equivalent: SET DEFAULT . SET(...) : Set a given value. This one is not part of the SQL standard and is entirely handled by Django. DO_NOTHING : Probably a very bad idea since this would create integrity issues in your database (referencing an object that actually doesn’t exist). SQL equivalent: NO ACTION .
    Source: Django documentation
    See also the documentation of PostGreSQL for instance.
    In most cases, CASCADE is the expected behaviour, but for every ForeignKey, you should always ask yourself what is the expected behaviour in this situation. PROTECT and SET_NULL are often useful. Setting CASCADE where it should not, can potentially delete all your database in cascade, by simply deleting a single user.
    3. 테이블의 조작(정방향 조회는 필드에 따라, 반방향 조회는 테이블 이름에 따라)
    1. 기본 조작(추가, 삭제, 수정, 조사)
    #  
    models.Tb1.objects.create(c1='xx', c2='oo') #      ,           **kwargs
    
    obj = models.Tb1(c1='xx', c2='oo')
    obj.save()  #     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()                                                 #       
    

    2. 표 조작 진급(소박의 더블 밑줄) _set를 이용하여 테이블 간의 조작을 연결하다
    #     
    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  11、22、33   
    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'))
       SQL  :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)
    
    #   
    get  :
        #  :    id 3     。
        #             ,          
        BookInfo.objects.get(id=3)
    
    all#  :        。
        BookInfo.objects.all()
    
    filter"""
            :(    )
                  __   = 
        """
                34      :
        a)      :exact。
            #  :     1   。
            BookInfo.objects.get(id=1)
        b)    (   sql  like)
            #  :      ' '   。contains
            BookInfo.objects.filter(btitle__contains=' ')
            #  :     ' '      endswith   :startswith
            BookInfo.objects.filter(btitle__endswith=' ')
        c)    isnull
            #  :          。isnull 
            select * from booktest_bookinfo where btitle is not null;
            BookInfo.objects.filter(btitle__isnull=False)
        d)     in
            #  :  id 1 3 5   。
            select * from booktest_bookinfo where id in (1,3,5);
            BookInfo.objects.filter(id__in = [1,3,5])
        e)     gt(greate than) lt(less  than) gte(equal)       lte    
            #  :  id  3   。
            Select * from booktest_bookinfo where id>3;
            BookInfo.objects.filter(id__gt=3)
        f)    
            #  :  1980      。
            BookInfo.objects.filter(bpub_date__year=1980)
            #  :  1980 1 1       。
            from datetime import date
            BookInfo.objects.filter(bpub_date__gt=date(1980,1,1))
    
    exclude    :
        #  :  id  3     。
        BookInfo.objects.exclude(id=3)
        
    order_by    :
          :          。     ,     “-#  :         ,  id        。
        BookInfo.objects.all().order_by('id')
        #  :         ,  id        。
        BookInfo.objects.all().order_by('-id')
        #  : id  3                 。
        BookInfo.objects.filter(id__gt=3).order_by('-bread')
    

    3. 기타
    # 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()
    
    

    4. 테이블 연결 작업(이중 밑줄 사용)
  • 모델 테이블 구조 인스턴스
  • 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
    
    

    1. 일대일 운영
    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())
    

    2. 일대다
  • 일대일 유사
  • 1. 검색 조건 사용__ 연결
  • 2, 값 획득 시 사용. 연결

  • 3. 다대다
    user_info_obj = models.UserInfo.objects.get(name=u'   ')
    user_info_objs = models.UserInfo.objects.all()
    
    group_obj = models.UserGroup.objects.get(caption='CEO')
    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()  # __set
    print user_info_obj.usergroup_set.all().filter(caption='CEO')
    print user_info_obj.usergroup_set.all().filter(caption='DBA')
    

    5. 확장(파일 업로드)
  • 사용자 정의 파일 업로드
  • def upload_file(request):
        if request.method == "POST":
            obj = request.FILES.get('fafafa')
            f = open(obj.name, 'wb')
            for chunk in obj.chunks():  # chunks          
                f.write(chunk)
            f.close()
        return render(request, 'file.html')
    
  • Form 업로드 파일 인스턴스
  • # Form
    class FileForm(forms.Form):
        ExcelFile = forms.FileField()
        
    # Model
    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
    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
    

    6. 대량 삭제
  • 일반 삭제: models.SyncRecord.objects.filter(create_time__lte=clear_timestamp).delete() 여과된 데이터에 따라 직접 삭제 호출
  • 페이지, limit이 포함될 때django는 직접적인 대량 조작을 지원하지 않습니다
  • 하위 조회 이용 가능:
  • models.SyncRecord.objects.filter(
            pk__in=(models.SyncRecord.objects.order_by('create_time').values_list('pk')[:5])
    ).delete()
    
    # django ORM          sql  page/limit  ,   orm  sql ,        page/limit
    
  • 그러나 낮은 버전 mysql(예: 5.7.2)에서는 이러한 검색을 지원하지 않습니다.
  • 로 변환할 수 있습니다.
    id_query_set = models.SyncRecord.objects.order_by('create_time')[:clear_count].values_list('id')
    # django       queryset  
    clear_id_list = [int(i[0]) for i in id_query_set]
    models.SyncRecord.objects.filter(id__in=clear_id_list).delete()
    

    좋은 웹페이지 즐겨찾기