drf serialization and deserialization, the concept of group table

Before serialization and de-serialization, we need to know the point

Knowledge model table

The concept of base table:

  When the base table can inherit other tables, which can inherit the field for many tables there are several fields can be used to create a base table

Base table created:

class BaseModel(models.Model):
    create_time = models.DateTimeField(auto_now_add=True)
    is_delete = models.BooleanField(default=False)

    class Meta:
        # abstract默认为False
        # abstract为True不会创建此表
        abstract = True

Off the foreign key field is connected with reverse lookup on_delete

class AuthorDetail (BaseModel): 
    adders = models.CharField (MAX_LENGTH = 255 ) 
    Mobile = models.CharField (MAX_LENGTH =. 11 ) 
    author = models.OneToOneField ( 
        to = ' the Author ' ,
         # reverse lookup is through related_name, by default all lowercase table name 
        # when virgin ORM, when a plurality of reverse lookup, and needs _set, but the related_name Once defined, when a plurality of reverse lookup, nor does it require _set 
        the related_name = ' Detail ' ,
         # off association 
        # slowing database pressure 
        db_constraint = False,
         # under on_delete default is models.CASCADE
        # Do_nothing author records deleted. Details without any modification 
        # set_default of the record is deleted, author one field becomes the default value you set, but you want to set in advance default 
        # when SET_NULL of the record is deleted, author a on a field will become empty (null) should be set in advance = True null 
        on_delete = models.DO_NOTHING 
    ) 

    class Meta: 
        db_table = ' day71_author_detail ' 
        verbose_name = ' author details ' 
        verbose_name_plural = verbose_name 

    DEF  __str__ (Self):
         return  ' % S details ' % self.author.name

Note:

  Under disconnection case, two tables have no relationship database, the database will not go to operating cascade delete cascading update

  We added on_delete = models.CASCADE let orm cascading deletes through logic

Serialization and deserialization (ModelSerializer)

Serialization

class Publishserializers (serializers.ModelSerializer):
     class Meta -: 
        Model = models.Publish 
        fields = ( ' name ' , ' adders ' ) 


class Bookserializers (serializers.ModelSerializer):
     # custom field must be written in the fields 
    # understand: the manner the sequence of the fields, the fields must be declared in 
    # custom table even depth - sequences of the way 
    # If the self-defined fields when the field the same name and model class, will take custom fields 
    publish = Publishserializers ()
     class Meta: 
        model = models.Book 
        Fields = (' Name ' , ' . Price ' , ' publish ' , ' get_author ' , ' Gender ' ) 

        # all fields 
        # fields = '__all__ is' 
        # and fields do not coexist, exclude excluded which fields 
        # the exclude = ( 'ID', 'is_delete' , 'the create_time') 
        # automatically connects depth table 
        # depth. 1 =

Sequence of fields may be added to the sequence of the model class attributes plug,

Simple point is, in the model defined in the class methods, preferably decorative property decorator

# Serialization Pluggable Properties - complete custom field name query completion table even 
    @Property
     DEF get_author (Self):
         # Print (self.authors, type (self.authors)) 
        return self.authors.values ( ' name ' , ' Age ' )

Pluggable model class attributes, fields in the sequence of writing not writable

 

Note:

  Custom Fields is best not to duplicate names and model fields in the table

Deserialization

class BookDeserializers (serializers.ModelSerializer):
     class Meta -: 
        Model = models.Book 
        Fields = ( ' name ' , ' . price ' , ' publish ' , ' the authors ' )
         # extra_kwargs deserialization added to the system verifies 
        extra_kwargs = {
             ' name ' : {
                 ' MAX_LENGTH ' : 10 ,
                 ' min_length ' :. 3,
                 # Required default is True, so the default Required 
                ' required ' : True,
                 ' error_messages ' : {
                     ' max_length ' : ' name up to 10 ' ,
                     ' min_length ' : ' Name the shortest 3 ' ,
                     ' required ' : ' name required ' 
                } 
            } 
        } 
    
    # local hook 
    DEF validate_name (Self, value):
        IF  ' G '  in value:
             The raise exceptions.ValidationError ( ' You chicken thief ' )
         return value 

    # global hook 
    DEF the validate (Self, attrs):
         # foreign key field pass over the front end is the id value, but the back-end will convert it to an object, 
        # If you pass over the id value is not in the database, an error directly, if we wrote raise_exception = True will be directly returned to the wrong front end 
        book_obj = models.Book.objects.filter (publish = attrs. GET ( ' publish ' ), name = attrs.get ( ' name ' ))
         # Print (book_obj) 
        IF book_obj:
             The raiseexceptions.ValidationError ({ " name " : ' title repeat ' })
         return attrs

 

Serialization and de-serialization can be combined, just above demonstrate the convenience

"" " 
. 1) Fields are provided for all the serialization and deserialization field 
2) extra_kwargs divided only sequences or anti-only sequence of fields 
    write_only: Anti-only serialization 
    read_only: only the sequence of 
    custom fields by default only the sequence of (READ_ONLY) 
3) set the desired deserializing system, local hooks, hooks and other global validation rules 
"" " 


class V2Bookserializers (serializers.ModelSerializer):
     class Meta -: 
        Model = models.Book 
        Fields = ( ' name ' , ' IMG ' , ' . price ' , ' the authors ' , ' publish ' , 'publish_name', 'get_author')
        extra_kwargs = {
            'img': {
                'read_only': True
            },
            'publish_name': {
                'read_only': True
            },
            'get_author': {
                'read_only': True
            },
            'name': {
                'max_length': 10,
                 ' Min_length ' :. 3 ,
                 ' error_messages, ' : {
                     ' MAX_LENGTH ' : ' name up to 10 ' ,
                     ' min_length ' : ' name shortest 3 ' ,
                     ' required ' : ' name Required ' 
                } 
            } 
        } 

    DEF validate_name ( Self, value):
         IF  ' G ' invalue:
             The raise exceptions.ValidationError ( ' You chicken thief ' )
         return value 

    DEF the validate (Self, attrs): 
        book_obj = models.Book.objects.filter (name = attrs.get ( ' name ' ), publish = attrs.get ( ' publish ' ))
         IF book_obj:
             The raise exceptions.ValidationError ({ ' name ' : ' the same title can not be repeated Press ' })
         return attrs

Remind again:

  Even the custom table depth (custom properties) defaults to only participate in the serialization read_only

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

When I was looking at the stars and saw the Taotao river, we saw the queens

 

Guess you like

Origin www.cnblogs.com/asdaa/p/11689849.html