day83-drf

The role of the base table (inherited)

class BaseModel (models.Model): 
    create_time = models.DateTimeField (verbose_name = ' Creation Time ' , auto_now_add = True) 
    is_delete = models.BooleanField (verbose_name = ' Delete ' , default = False)
     class Meta:      
        abstract = True                    # There the Model class attribute database migration will not be completed to produce a table 


class the Publish (BaseModel): 
    name = models.CharField (= the verbose_name ' publisher name ' , MAX_LENGTH = 32 ) 
    address = models.CharField (= the verbose_name 'Address ' , MAX_LENGTH = 64 ) 
    Phone = models.CharField (the verbose_name = ' Phone ' , MAX_LENGTH = 32)

 

Configuring static media files (image path)

settings.py: 

MEDIA_URL = ' / Media / ' 
MEDIA_ROOT = os.path.join (base_dir, ' Media ' ) 

models.py: 

class Author (BaseModel): 
    name = models.CharField (verbose_name = ' author ' , max_length = 32 ) 
    icon = models.FileField (the upload_to = ' icon ' , default = ' icon / icon.jpg ' )       # incoming path and the default path 
    telephone = models.CharField (the verbose_name = ' phone ' , MAX_LENGTH = 32 )

Other custom class model display fields: 
@Property 
DEF author_detail_list (Self): 
    author_detail_arr = []
     for author in self.authors.all (): 
        author_dic = {}       
        author_dic [ ' icon ' ] = settings.MEDIA_URL + STR (author .icon)        # author.icon object type, not serialize 
        author_detail_arr.append (author_dic)
     return author_detail_arr

 

The method of processing foreign key field model table

Foreign key process:

 1. Reverse query: the related_name = ' XXX '
 
2. Table Relationships (db_constraint + on_delete): 
    db_constraint = False disassociated database, i.e. without a database logic determination operation, but the operation is determined by the logical database orm 
    on_delete = models.CASCADE cascading deletes, many to many tables do not need to write, because the default cascading deletes 
    on_delete = models.SET_NULL, null = when True deleted, the foreign key field is empty 
    on_delete = models.SET_DEFAULT, = default 0 delete when foreign key field is 0 
    on_delete = models.DO_NOTHING when deleted foreign key field is not processed  
Case: 
class
AuthorDetail (BaseModel): CHOICE_SEX = ( (0, ' M ' ), ( 1, ' female ' ) ) Age = models.IntegerField (verbose_name = ' Age ' ) Sex = models.IntegerField (verbose_name = ' gender ' , choices = CHOICE_SEX, default = 0) info = models.TextField (verbose_name = ' personal details ' ) author = models.OneToOneField (verbose_name = ' author', to='Author', db_constraint=False, on_delete=models.CASCADE, related_name='detail')

 

Guess you like

Origin www.cnblogs.com/klw1/p/11361517.html