Beginner Django base 02

django's ORM operations

Before we know models.py this file, which is used to read the file data structure are taking this module each time the operating data

 

 

Common Fields

  Auto Field

int auto increment, must fill in the parameters primary_key = True. When the model, if there is no auto-increment, then automatically creates a column called id columns.

  IntegerField

An integral type, in the range -2147483648 to 2147483647.

  CharField

Character type, must provide max_length parameters, characters indicating max_length.

  DateField

Date field, the date format YYYY-MM-DD, corresponding to the Python datetime.date () instance.

  DateTimeField

Time field, the format YYYY-MM-DD HH: MM [: ss [.uuuuuu]] [TZ], corresponding to the Python A datetime.datetime () instance.

 

Create a table structure

 

#models.py

from django.db Import Models 


# the Create your Models here Wallpaper. 
class Nav (models.Model): 
    name = models.CharField (= 10 MAX_LENGTH, unique = True, 
                            the verbose_name = ' navigation name ' )   # MAX_LENGTH maximum number, unique is unique , verbose_name table Chinese name 
    is_delete = models.SmallIntegerField (default = 1, verbose_name = ' has been deleted ' )   # default defaults 
    create_time = models.DateTimeField (verbose_name = ' creation time ' , auto_now_add = True)   # auto_now_add insert data time, automatically take the current time
    = models.DateTimeField update_time (verbose_name = ' Modified ' , auto_now = True)   # auto_now modify the data, the time will automatically become 

    DEF  __str__ (Self):
         return self.name   # __str__ If you do not write print is an object, this name can be printed together with the value of 

    class Meta:   # additional information table structure 
        verbose_name = ' navigation table '   # Chinese name table 
        verbose_name_plural = verbose_name   # Chinese name table 
        db_table = ' NAV '   # table 
        # Ordering = [ 'update_time '] # when querying data, used to sort of 


classArticle This article was (models.Model): 
    title = models.CharField (= max_length 20, verbose_name = ' article name ' ) 
    Content = models.TextField (null = True, verbose_name = ' article content ' )   # null is null 
    img = models. ImageField (upload_to = ' article_img ' , null = True, verbose_name = ' picture of the article ' , 
                            default = ' article_img / 1.jpg ' )   # ImageField upload files, upload_to upload pictures automatically creates a article_img in MEDIA_ROOT path setting set folder Note to use the file upload module must be installed pillow
    = models.FileField File (upload_to = ' file_img ' , 
                             verbose_name = ' file picture ' )   # The only difference is FileField and ImageField ImageField can upload image format files, and FileField able to upload all the files 
    is_delete = models.SmallIntegerField (default = 1, verbose_name = ' has been deleted ' ) 
    NAV = models.ForeignKey (Nav, verbose_name = ' navigation the above mentioned id ' , on_delete = models.DO_NOTHING, db_constraint = False)   # foreign key 
    create_time = models.DateTimeField (verbose_name = ' creation time ' , auto_now_add =  True)
    update_time= models.DateTimeField(verbose_name='修改时间', auto_now=True)

    def __str__(self):
        return self.title

    class Meta:
        db_table = 'article'

Run to the database

  Python the Manage . Py makemigrations # generated migration file

  Python the Manage . Py the migrate # synchronized to the database

 

djangoORM CRUD

# This represents three django tell me which database to operate 
Import django, os 

os.environ.setdefault ( ' DJANGO_SETTINGS_MODULE ' , ' dj_test.settings ' )   # set django profile 
django.setup ()   # Configure and verify 

from the User Import Models   # find the corresponding table structure file 

# new 
models.Nav.objects.create (name = ' my diary ' ) 

# this will also add 
nav_obj = models.Nav (name = ' I feel ' , is_delete = 1 ) 
nav_obj.save () 

# inquiry
# GET method to query, then have to ensure that this data is only a check out, can 
the Result = models.Nav.objects.get (is_delete = 1 )
 Print (result.name) 

# add the search results filter out likely is more than 
result0 = models.Nav.objects.filter (is_delete = 1, name = ' I feel ' )   # and 
result1 = models.Nav.objects.filter (name__contains = ' I ' )   # fuzzy query 
result1_1 = models .Nav.objects.filter (create_time__endswith = ' 84 ' )   # query matches the end character 
result1_2 = models.Nav.objects.filter (create_time__startswith = ' 2019 ' )  # Query matches the beginning characters 
result1_3 = models.Nav.objects.filter (create_time__isnull = True)   # inquiry is empty of 
result2 = models.Nav.objects.filter (id__gt = 0)   # greater than 0 
result3 = models.Nav.objects. filter (id__gte =. 1)   # greater than or equal. 1 
result4 = models.Nav.objects.filter (id__lt = 2)   # less than 2 
result5 = models.Nav.objects.filter (id__range = [. 1,. 5])   # between a range 
= models.Nav.objects.filter result6 (id__in = [1, 2,. 3,. 5,. 6])   # in 
result7 = models.Nav.objects.exclude (id = 1)   # excluded, except for the id 1 

from Django .db.models Import Q 

result8Models.Nav.objects.filter = (Q (= name__contains ' . 6 ' ) | Q (= name__contains ' . 3 ' ))   # or 

result9 . Models.Nav.objects.all = () filter (name__contains = ' . 6 ' )   # All acquired data table which 
result10 models.Nav.objects.all = (). filter (name__contains = ' . 6 ' ) .count ()   # COUNT may acquire the number of 
result11 = models.Nav.objects.all (). filter ( = name__contains ' . 6 ' ) .values ()   # values returned dictionary display 
result12 = models.Nav.objects.raw ( ' SELECT * from NAV' )   # Execute native SQL 

# Review 

# this method is to modify the value of a re-assignments of 
n-= models.Nav.objects.get (= ID. 1)   # parimy Key 
n.name = ' WO album 2 ' 
n.is_delete . 1 = 
n.save () 

models.Nav.objects.all (). update (is_delete = 0)   # update all data tables which 
models.Nav.objects.filter (name__contains = ' I ' ) .Update (is_delete. 1 = )   # The condition 

# delete 

models.Nav.objects.all (). delete ()   # delete all data tables which 
models.Nav.objects.filter (= id__lt. 3) .Delete ()   # deleted according to the conditions

the n- = models.Nav.objects.get (the above mentioned id = 3)   # parimy Key deleted individually 
n.delete () 

# reverse lookup 
art_obj = models.Nav.objects.get (name = ' My Diary 3 ' )
 Print (art_obj .article_set.filter ())   # foreign key reverse lookup 

# nav_obj.article_set.add (art_obj) # add 
# nav_obj.article_set.remove (art_obj) # delete 
# nav_obj.article_set.clear () # empty

 

Guess you like

Origin www.cnblogs.com/RainBol/p/11718456.html